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 of landing in its acceptable subset under the proposal, then one sample's success probability is at most after such coordinates. Independent uniform coordinates with a fixed acceptable range fraction 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 to near-good plans, independent candidates contain at least one with probability . When adding coordinates makes 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 , 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 for every time step . 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 , , , , , and . Here we keep , , and , but write the state as to emphasize that it may be latent, and write the stage and terminal costs as and . Thus corresponds to the previous chapter's , while and correspond to and .
We work with a deterministic, differentiable dynamics model
where 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 is continuous. The initial state is given and fixed. Over a horizon of transitions we accumulate the cost
where is the stage cost at time and is an optional terminal cost. The actions are the inputs to a recurrence, and 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.
In Recurrent State-Space Models we differentiated the loss with respect to model parameters 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 . It has a direct path to the stage cost and a path through the next state 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 as
The sensitivity of a future state to a past action is then a product of state Jacobians:
Read this product from right to left: the action perturbs through , 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 have operator norm at most a common , 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 and share the same suffix. A naive scalar implementation that forms each horizon-length product independently performs transition multiplications; one backward sweep performs . The adjoint (co-state) recursion is reverse-mode autodiff organized to reuse those suffixes.
Define the adjoint vector
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 directly. Because feeds into every later state and cost through the dynamics, this sensitivity already accumulates everything that happens downstream of time . At the end of the horizon the adjoint is just the terminal cost gradient:
Now walk backwards. The state influences the objective in exactly two ways: through the stage cost , and through the next state , whose adjoint we already have. The chain rule gives
The transpose appears because depends on through , and is a column vector. Under the local linearization, . Pulling a gradient back through the transition therefore multiplies by , 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 enters the objective only through and through :
where:
- : the direct sensitivity of the stage cost at time to the action taken at time
- : the action Jacobian, mapping an action perturbation into a next-state perturbation
- : the adjoint of the next state, which aggregates the sensitivity of every future cost
One backward sweep computes and every action gradient. Its arithmetic cost is a small constant multiple of the forward evaluation. A standard uncheckpointed implementation uses 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 and 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 by repeated multiplication uses multiplications by . With the terminal seed available, the adjoint sweep needs multiplications to produce ; together, are the adjoints required by all action gradients.
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}"
)
This is the cheap gradient principle: reverse mode computes a full 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
and therefore
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 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 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 with . Holding the sampled noise fixed then gives a pathwise gradient for a Monte Carlo objective. When reparameterization is unavailable, differentiating yields the ordinary term plus the likelihood-ratio term , 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 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 , action-sequence planning is a constrained finite-dimensional optimization problem:
where is the admissible action set. Independent limits form a box: with shared scalar limits it is , and in general it is . 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 . 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: . 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:
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
and optimize the unconstrained variable . In exact real arithmetic, every finite maps into the strict interior of the box. In floating-point arithmetic, can round to , 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 is large, 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 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 , define and ; let denote the corresponding gradient blocks of the local action cost-to-go , and let denote its Hessian blocks. When the unconstrained local control subproblem is well posed, typically after regularization makes 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:
and, when is positive definite, the local feedforward perturbation is . At each time step the sweep forms , , and the local linear terms from the stage-cost derivatives, , , 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 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
with the target state, weighting state error, and penalizing effort. For physical coordinates with documented units and suitably structured, calibrated and , the terms can be interpreted as weighted state-error and action-effort contributions. For a learned latent state, the first term is a -weighted squared discrepancy—a squared seminorm if 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 and target in , a decoded cost with in 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 , a smooth alternative is , a softplus approximation to the hinge violation rather than to a binary indicator. A Gaussian goal bonus, , is another option. At fixed distance , its state-gradient magnitude is and is largest at . In the tail , shrinking further weakens the gradient; for , shrinking it can strengthen the gradient. Tune to the candidate-distance distribution, and narrow it as candidates approach only while preserving a useful signal.
- Logarithmic barriers. For a barrier weight , an inequality on a strictly feasible trajectory can be represented by . The term inherits 's regularity in the strict interior: it is smooth there when is smooth, and merely differentiable there when is merely differentiable. It diverges to as . At any finite positive 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 , softer alternatives add . 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
The added terms telescope to the fixed constant , so they do not change the ordering of feasible action sequences. Omitting the terminal correction leaves the residual , which is generally action-dependent and can change the optimum when 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:
assuming the continuation cost is finite and uses the same dynamics, constraints, costs, and information pattern as the planner. If is the exact optimal continuation cost, the subproblems attain their minima, and , 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 -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
where solves the discrete algebraic Riccati equation
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 . 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 . That terminal-state adjoint propagates through the rollout and contributes a gradient to every earlier action.
For direct action optimization. If denotes a reward or return to maximize and is differentiable in a continuous action, one ascent iteration is
with appropriate constraint handling for constrained actions, such as projection or reparameterization for simple action bounds. This uses a reward convention, unlike the continuation cost above; for an action cost-to-go, the corresponding update uses the negative gradient. Each iteration differentiates one 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 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
If the state Jacobians were constant, for all , this product would be . For a scalar , or for a normal matrix whose relevant modes are excited, its asymptotic scale follows the eigenvalue magnitudes:
- If , the product decays geometrically. The influence of early actions on late states vanishes.
- If 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 , the modal magnitude changes little per transition. Over transitions it remains near one only when is small, and negative 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 . 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 , its smallest positive normal value is about , and subnormal values extend to about . With and , ; with , the product is about at and at , still finite, but it overflows near . In the other direction, is still normal; it reaches the normal/subnormal boundary only near . 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 and , respectively, ; if is only an enclosing interval, then . Gradient descent with step contracts Euclidean iterate error by at most per step when is the largest eigenvalue; a constant-factor reduction can therefore take on the order of 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 with . The final-state sensitivities are and . Away from a stationary terminal cost, the common terminal derivative cancels in their ratio, so the late-action gradient is about 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 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 . 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 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 , 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 , 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 stays near identity only when is controlled, not merely when 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 to 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 , use the ordinary 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 , 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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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 and , with acceleration held constant over each sampling interval. Their exact zero-order-hold discretization at time step is
The cost is quadratic with target :
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 is an affine function of the whole action sequence:
where collects the actions and has columns
Substituting into the cost and collecting terms gives a quadratic function of :
with for all in this example. The gradient is affine in the actions:
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 .
The objective is strictly convex. is a sum of positive semidefinite terms plus , so when . The unique local minimum is the global minimum,
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 . 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 -Lipschitz gradient, fixed-step gradient descent with 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.
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 = 12The 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 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.
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 + terminalNow 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.
## --- 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 bObjective 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.
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 to ; the all-zero vector used in the nearby gradient checks is separate from that run. We use . 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.
## 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}")
(<Figure size 900x750 with 1 Axes>, <Figure size 900x750 with 1 Axes>)


The objective decreases throughout the plotted run. Under this fixed budget, the trajectory approaches and overshoots the target position, ending near rather than settling exactly at . 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 for increasing horizons in this fixed double-integrator problem. The true action Hessian is , which has the same condition number as . Horizon growth need not worsen every system, but it does here.
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}")
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 , the Hessian has largest eigenvalue . Gradient descent with step contracts Euclidean iterate error by at most per step. For and , reaching is therefore guaranteed once
For an integer iteration count, take the ceiling of the right-hand side. When , the step 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 quadratic using the same learning rate.
## 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")
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.
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)}")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_shortCumulative 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

The two-step controller without a terminal value overshoots the target by about in this deterministic run. Adding the Riccati value reduces peak overshoot to about and lowers the 25-step cumulative cost by about 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 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 and , the general derivative is
At the code's evaluation point with all actions zero, and this reduces to . We sweep nonnegative and the horizon, recording the first-action gradient magnitude.
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)(<Figure size 900x1050 with 1 Axes>, <Figure size 900x1050 with 1 Axes>)


The left panel shows the predicted exponential decay and growth for this terminal-only objective: for the first-action gradient tends toward zero, for it grows, and at it stays constant. More generally, contraction occurs when . At fixed , the first-action magnitude is times the last-action magnitude; with 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 . This sign-like normalization resembles Adam's first update only when moment state starts at zero, gradients dominate , and clipping, weight decay, or other interventions do not materially alter the coordinatewise first update.
## 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}"
)
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 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 , the recursion is and ; the action gradient is . 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 . 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 in a parameterization gives strict-interior feasibility. Finite-precision may round to ; 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 , an -factor sensitivity product has magnitude . For a constant normal Jacobian, each excited eigenmode scales as , and its Euclidean induced operator norm (spectral -norm) is . 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
Reference
Citation details
Cite or share this article.
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 HandbookStay up to date
Get articles, book updates, and news delivered to your inbox.
No spam, unsubscribe anytime.
Join the community
Sign in to remove popups, track your reading progress, and join the discussion.

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