Differentiable Model Predictive Control on the GPU
Paper · 2025 · Emre Adabag, Marcus Greiff, John Subosits et al.
Summary
A controller that plans ahead must repeatedly predict how a system will respond to its actions. A learning system that tunes the controller has a further job. It must determine how those planned actions would change if it adjusted a cost weight or a physical parameter. The paper introduces DiffMPC, a tool that performs both computations on a graphics processing unit. Its aim is to make predictive controllers practical to train on batches of simulated experience while preserving the explicit dynamics and objectives that make their decisions possible to inspect.
The main design choice concerns how to solve a problem that stretches across a sequence of future times. A conventional optimal-control solver can exploit the fact that neighboring times are directly connected, but frequently does so by processing those times in order. DiffMPC uses those same connections to organize work that can proceed simultaneously. It builds a succession of quadratic approximations to the control problem and solves each using preconditioned conjugate gradient, an iterative method whose main matrix operations can work on many timesteps at once. The gradient computation uses the same matrix structure as the forward solve. When successive problems are similar, both computations can also start from earlier solutions.
In the paper’s quadratic reinforcement-learning benchmark, DiffMPC on the GPU is about 4 times faster than the fastest baseline on the problem highlighted in the main comparison. The nonlinear attitude-stabilization benchmark reports an roughly 7.3× backward-pass speedup over Trajax. On a cart-pole imitation task, DiffMPC reduces the time needed to run the training procedure by approximately a factor of 2. The CPU results are more mixed. The timing advantage depends on which hardware executes the solver and how the work is distributed across it.
The authors also use DiffMPC to tune a controller for a Toyota Supra drifting through puddles. Training varies the starting conditions and where grip drops in simulation. On randomized simulated trials, the tuned controller completes the maneuver in 100% of trials, compared with 70% for the manually tuned baseline. It also transfers from training on a figure-8 path to a circular drift on the car. The learned settings lead the controller to accept greater error in following the requested sideslip in exchange for less aggressive actions. The physical tests demonstrate deployment of the learned controller, with another quadratic-program solver handling the calculations on the vehicle.
Deep dive: Differentiable Model Predictive Control on the GPU
DiffMPC uses GPUs to speed up predictive control and its gradients, with tests in reinforcement learning, imitation learning, and wet-road drifting. · about 36 minutes to read
The problem and its context
Planning ahead and learning what to plan
A predictive controller starts with the current state of a system and chooses actions by looking ahead. It predicts states that could follow from different actions, scores those predictions against an objective, and chooses a plan that respects the dynamics assumed by the controller. In closed-loop use, the controller takes an action from that plan, receives an updated state, and plans again. Replanning matters because the state the system actually reaches can differ from the state the controller predicted.
The plan depends on more than the starting state. A designer must decide how costly it is to depart from a reference, how strongly to discourage large control inputs, and which physical parameters to use when predicting the system’s response. These choices affect one another. A controller might track a reference tightly because departures are expensive in its objective or because its assumed dynamics make the required correction seem easy. Changing what the controller assumes about the system can therefore change its behavior even with the same objective.
Differentiable optimization gives a training procedure access to those dependencies. A controller produces an action by solving an optimization problem. Its derivative describes how that action responds to small changes in the problem’s parameters near the solution. A training loss can use that derivative to suggest changes to the controller’s parameters. The paper presents this as a way to retain the structure of an optimization-based controller while using data to tune parts of it that otherwise require expert effort. The optimization can also incorporate constraints that are known in advance. This is the connection the authors draw between optimal control and machine learning.
The paper describes uses of differentiable control in motion planning, parameter estimation, controller tuning, reinforcement learning, and imitation learning. The examples share a computational difficulty. During training, the same optimization may be called for many initial states, during many steps of an episode, and again after the parameters change. A method that makes the forward solve faster helps only part of this workload. Training also needs the backward pass, which propagates the effect of the optimized decision to the parameters that produced it.
Why time structure matters
In an optimal-control problem, the dynamics connect the state at one time to the state and action at the preceding time. This gives the optimization a sparse structure. A constraint concerning one transition has no direct dependence on variables far from that transition. The final plan still reflects the entire horizon. The local pattern simply tells the solver where the direct dependencies lie.
Earlier optimal-control methods often exploit that pattern through Riccati recursion. The iterative linear quadratic regulator, or iLQR, repeatedly approximates the problem around a trajectory and uses a recursion to solve the resulting local control problem. Each stage of the recursion depends on information obtained from another stage. That dependence provides an efficient way to solve the structured problem on a CPU. It also limits how much work a GPU can do simultaneously for a single trajectory. Processing many independent trajectories together can supply parallel work across the batch, while each trajectory retains the sequential recursion. The paper’s hardware question concerns how much more can be gained from GPU and parallel computing.
The authors distinguish between general-purpose differentiable optimization tools and tools designed for optimal control. As discussed in the paper’s background on implicit differentiation, an optimization problem can itself serve as a differentiable layer. General-purpose tools can cover a wide range of such problems and frequently support GPUs. The price of generality is that the solver may have less opportunity to use the particular structure of time-indexed control. The paper cites a foundational example of differentiable optimization layers in its account of this line of work. OptNet
The comparison with Theseus makes the structural distinction concrete. Theseus handles nonlinear least squares. To express the control benchmark in that form, the authors use actions as variables and compute the states by rolling those actions through the dynamics inside the objective. This is a way to eliminate explicit dynamics equalities. It also means that a later state in the rollout can depend on many earlier actions. A solver that keeps the states as variables instead can retain a separate equality for each transition and use the pattern of nearby dependencies in its linear algebra.
Other differentiable solvers already specialize in optimal control. The paper identifies mpc.pytorch and Trajax as particularly close comparisons because they use time structure and can execute on GPUs. Both rely on Riccati recursions. The authors also describe optimal-control tools whose algorithms are geared toward CPU execution. The gap DiffMPC addresses is a combination of capabilities that those approaches offer in different proportions: differentiating the solution, using the sparse structure of the control problem, and making parallel work available within that structure.
The immediate precursor is MPCGPU. The paper credits it with a preconditioned conjugate gradient routine that exploits sparsity along the prediction horizon and is suitable for replanning, including individual problem instances. DiffMPC takes that approach to the linear solve and adapts it to a setting in which the derivatives of the solution matter as well. A forward solution and a backward derivative require different inputs, but both lead to closely related systems of equations. MPCGPU
The method, step by step
From a control problem to a training signal
DiffMPC takes a parameterized control problem and an initial guess for its solution. The control problem specifies which trajectories are dynamically possible and which are preferable. The initial guess gives the optimizer a place to construct its first local approximation. DiffMPC solves that approximation, uses it to update the trajectory, and repeats as needed. Once a training objective supplies a derivative with respect to the resulting trajectory, DiffMPC converts it into a derivative with respect to the controller parameters.
Several kinds of repetition occur in this process. There are the predicted timesteps inside the optimization horizon, the iterations used to solve the optimization, and the repeated calls to the controller in an episode. A batch supplies an additional set of independent problems. DiffMPC exposes parallelism across prediction steps and problem instances while retaining the dependencies between successive optimizer iterations and between successive states of a closed-loop rollout.
From a candidate trajectory to a parameter gradient
The steps in order.
What the controller optimizes
The controller compares trajectories over a finite horizon. It pays a state cost at the final predicted time as well as at the earlier times. Each action steers a transition, so the action costs end before the final state. A separate equality specifies the starting state. In Unicode notation, the paper’s optimal-control problem is
z*(θ) = arg min_{z=(x,u)} [Σ_{t=0}^{T} cˣₜ(xₜ; θ) + Σ_{t=0}^{T−1} cᵘₜ(uₜ; θ)] subject to fₜ(xₜ₊₁, xₜ, uₜ; θ) = 0 and x₀ = xₛ(θ)
Here θ is the collection of parameters, and z is the decision vector containing the state sequence x and action sequence u. The star denotes the solution chosen by the optimization, and arg min denotes the argument minimizing the bracketed cost. The index t counts predicted timesteps and T is the prediction horizon. The sums Σ collect the state costs cˣₜ and action costs cᵘₜ. The state and action at time t are xₜ and uₜ, and xₜ₊₁ is the next state. For each transition, fₜ is a residual that must equal zero. The initial state x₀ equals the supplied state xₛ, which can depend on θ.
The residual form is useful because the equations can involve the next state directly. DiffMPC can keep that state among its decision variables while asking the optimizer to make the residual vanish. Each transition still touches a small set of neighboring variables. The objective has a complementary structure. The state and action costs are separate at each time, so their second derivatives occupy distinct blocks in the local quadratic problem.
The parameter vector can represent several kinds of quantities. An entry might change how much the controller values a small tracking error. Another might change the physical prediction for a given action. The paper also allows parameters to come from a preceding component in a differentiable system. The solver’s role is to compute how the solution responds to θ, leaving the choice of what θ represents to the application.
Build a quadratic problem around the current trajectory
The original problem can be non-convex. DiffMPC uses sequential quadratic programming, or SQP, which makes the next computation more tractable by replacing the local costs with quadratic functions and the transition equalities with linear ones. The optimizer solves the resulting quadratic program, or QP, and uses the result to propose a change to the original trajectory. Whenever the trajectory changes enough to warrant another iteration, the local functions are evaluated again.
The cost blocks come from first and second derivatives evaluated at the current guess. With the guess understood in the arguments, the paper gives the coefficients as
(Qₜ, qₜ) = (∇²cˣₜ(xₜ; θ), ∇cˣₜ(xₜ; θ)), (Rₜ, rₜ) = (∇²cᵘₜ(uₜ; θ), ∇cᵘₜ(uₜ; θ))
The state curvature matrix is Qₜ and the state gradient is qₜ. The action counterparts are Rₜ and rₜ. The symbol ∇ denotes a gradient and ∇² denotes the Hessian, the matrix of second derivatives. Each derivative is taken with respect to the argument of its cost, xₜ for the state and uₜ for the action, with θ fixed for the solve at hand. The gradients give the local linear terms of the cost approximation in displacement coordinates. The authors project the curvature blocks onto the positive definite cone so the quadratic terms have positive curvature in every non-zero direction.
The affine equalities are built from the derivatives of each transition residual. It helps to name the current trajectory explicitly when describing how these derivatives are used.
(Aₜ⁺, Aₜ, Bₜ) = (∂fₜ/∂xₜ₊₁, ∂fₜ/∂xₜ, ∂fₜ/∂uₜ) evaluated at (x̄ₜ₊₁, x̄ₜ, ūₜ; θ)
The bars distinguish the current guess from variables in the next subproblem. The partial derivative symbol ∂ indicates which argument changes while the others are held fixed. Aₜ⁺ is the derivative with respect to the next state, Aₜ is the derivative with respect to the current state, and Bₜ is the derivative with respect to the current action. The superscript plus on Aₜ⁺ indicates which time its block acts on. It has a different meaning from the plus sign used later to label a candidate solution.
Aₜ⁺xₜ₊₁ + Aₜxₜ + Bₜuₜ = Cₜ, Cₜ = Aₜ⁺x̄ₜ₊₁ + Aₜx̄ₜ + Bₜūₜ − fₜ(x̄ₜ₊₁, x̄ₜ, ūₜ; θ)
Here Cₜ is the constant right-hand side obtained when the linear approximation is written in state and action coordinates. The unbarred variables belong to the candidate trajectory. Subtracting the residual at the current guess ensures that the equality includes the transition error already present in that guess. All these coefficients can be calculated independently across transitions once the current trajectory has been supplied.
With the linear cost terms denoted as in the paper’s QP, the subproblem objective has the following form.
min_{z=(x,u)} [Σ_{t=0}^{T}(½ xₜᵀQₜxₜ + qₜᵀxₜ) + Σ_{t=0}^{T−1}(½ uₜᵀRₜuₜ + rₜᵀuₜ)]
The superscript ᵀ means transpose, so each quadratic or linear product in the sum is a scalar. The factor ½ is the convention for writing the curvature term of a quadratic expansion. The objective uses the state blocks Qₜ and qₜ, and the action blocks Rₜ and rₜ. The transition equations and the specified initial state complete the QP. The local Taylor form uses the first derivatives as coefficients on displacements from the guess. Writing the same quadratic in absolute coordinates shifts its linear coefficients by the curvature times the expansion point. The paper uses the same state and action letters in its local derivative definitions and its displayed QP. The sparse solve applies in either coordinate convention.
Express the solution as a system of equations
The forward and backward passes both use the first-order optimality conditions. For a general equality-constrained problem, the paper calls the objective f and the equality residual g. In that part of the notation, f is a scalar objective, unlike fₜ in the control formulation, which is a vector of dynamics residuals.
L(z, λ, θ) = f(z, θ) + λᵀg(z, θ)
The Lagrangian L combines the objective f with the constraints g using the multiplier vector λ. The variable z and parameter vector θ have the same roles as in the control problem. Each multiplier corresponds to an equality. The product λᵀg gives a scalar contribution from those equalities.
F(z, λ, θ) = (∇z L(z, λ, θ), g(z, θ)) = 0
Here F stacks the Karush–Kuhn–Tucker conditions, or KKT conditions, for the equality-constrained problem. The first entry, ∇z L, is the gradient of the Lagrangian with respect to the decision vector. Its vanishing expresses stationarity. The second entry, g, vanishes when the equalities are satisfied. The joint zero denotes both requirements. In a QP, these conditions are linear in the decision variables and multipliers.
[G Hᵀ; H 0] [z; λ] = [−b; d]
In this display, the notation within square brackets marks block rows. G collects the curvature blocks Qₜ and Rₜ along its diagonal, following the alternating time order of states and actions. H is the matrix of linear equalities. Its first row of blocks selects the initial state, and later rows of blocks encode neighboring states and their intervening action through Aₜ, Bₜ and Aₜ⁺. The vector b stacks the linear cost terms, ending with the terminal state term, and d stacks the initial state xₛ and the transition constants Cₜ. The lower-right zero is a matrix block. The equality residual depends on the decisions z, so it has no multiplier coefficient of its own.
This form shows why solving the quadratic problem is also a matter of preserving locality. Multiplying by H uses neighboring parts of the trajectory. Multiplying by its transpose sends contributions from each constraint back to the variables it touches. Multiplying by the inverse of G can be separated into state and action blocks. DiffMPC combines these operations before solving for the full trajectory.
Reduce the system to constraint multipliers
DiffMPC first eliminates the decision vector using the top row of the KKT system. The matrix left after elimination is the Schur complement. It acts only on the equality multipliers.
S = −HG⁻¹Hᵀ, γ = d + HG⁻¹b
The matrix S is the Schur complement. The superscript −1 denotes a matrix inverse, which here acts on the independent curvature blocks of G. The vector γ is the resulting right-hand side, assembled from d and the contribution of the linear objective b. H and Hᵀ move between the space of decisions and the space of constraints.
Sλ = γ, z = −G⁻¹(b + Hᵀλ)
The first equation determines the multipliers λ. The second recovers the trajectory z once they are known. Because each block of G acts on a state or action separately, recovery at different times can proceed in parallel. Neighboring multipliers enter a state update through the transitions involving that state. An action update needs the multiplier for its own transition.
The Schur matrix is block tridiagonal. Its non-zero blocks lie along the main diagonal and the immediately neighboring block diagonals. To see why, consider two transition constraints. If they share a state, elimination through G can couple their multipliers. If their times are farther apart, they have no shared variable through which a diagonal block of G can couple them. The initial-state constraint is the special case at the first end of this chain.
ϕₜ = AₜQₜ⁻¹Aₜᵀ + BₜRₜ⁻¹Bₜᵀ + Aₜ⁺Qₜ₊₁⁻¹(Aₜ⁺)ᵀ
The block ϕₜ is the diagonal contribution for transition t in the positive-sign matrix inside the expression for −S. Its terms come from the current state, the current action, and the next state. Each term uses the corresponding derivative block and inverse curvature. The initial-condition block instead uses the inverse of Q₀.
χₜ = AₜQₜ⁻¹(Aₜ₋₁⁺)ᵀ
The block χₜ describes a coupling across the shared state at time t. In the first such block, the preceding coefficient Aₜ₋₁⁺ is the identity I because the initial-state equality selects that state directly. An identity matrix leaves the vector it multiplies unchanged. Each block on one side of the main diagonal has its transpose on the other side. The paper’s symmetric stair preconditioner retains a block tridiagonal pattern as well, using inverse diagonal blocks and selected neighboring interactions.
The same locality appears in trajectory recovery. For a nonterminal stage the paper writes
xₜ = −Qₜ⁻¹(qₜ + (Aₜ₋₁⁺)ᵀλₜ + Aₜᵀλₜ₊₁), uₜ = −Rₜ⁻¹(rₜ + Bₜᵀλₜ₊₁)
The multipliers here are indexed with λ₀ for the initial condition, and λₜ₊₁ for the transition leaving time t. The inverse state and action curvature blocks multiply the sum of the corresponding linear cost and constraint contributions. For t at the initial end of the horizon, Aₜ₋₁⁺ is again the identity. At the terminal end only the incoming transition contributes, so the recovered last state is
x_T = −Q_T⁻¹(q_T + (A_{T−1}⁺)ᵀλ_T)
The subscript T marks the terminal state, its curvature, its linear coefficient, and the multiplier of its incoming transition. The matrix A_{T−1}⁺ is the derivative of that last transition residual with respect to the terminal state.
Iterate on the sparse system and choose a step
Preconditioned conjugate gradient, or PCG, starts with a guess for the multipliers and calculates how far that guess is from satisfying the reduced equations. A preconditioner is an operator used to make the system easier for an iterative solver. The one in DiffMPC uses the block structure of the reduced system. Its application has a local pattern similar to the matrix multiplication in the residual, so preconditioning preserves the main opportunity for parallel work across time.
r = γ − Sλ, r̃ = Φ⁻¹r, p = r̃, η = rᵀr̃
Here r is the residual of the reduced system, separate from the action-cost term rₜ. The operator Φ⁻¹ is the symmetric stair preconditioning operation, and r̃ is the preconditioned residual. The search direction p initially equals that residual after preconditioning. The scalar η is the residual product used in the iteration and its stopping test. The paper places a minus sign in its definition of S. Conjugate gradient can equivalently be described in the positive-definite convention by reversing the signs of both sides of the reduced system and using the corresponding preconditioner sign.
y = Sp, α = η/(pᵀy), λ ← λ + αp, r ← r − αy
The vector y is the matrix applied to the search direction p. The scalar α is the conjugate-gradient step length, calculated from η and the inner product pᵀy. The left arrow denotes replacing the current value by the expression on its right. The update moves the multipliers and updates the residual by the matching amount.
r̃ ← Φ⁻¹r, η′ = rᵀr̃, β = η′/η, p ← r̃ + βp, η ← η′
The preconditioned residual is refreshed after the update. The prime marks the new residual product, and β is the ratio that determines how much of the old direction contributes to the new one. The loop uses a tolerance ϵ to decide when to stop. Applying the system matrix and the preconditioner can proceed across time blocks, while the inner products produce shared scalars and the iterations depend on previous iterations.
A useful initial multiplier guess can come from an earlier solve. This is warm-starting. A new prediction problem may begin from a state close to the state used for the previous plan, so its optimality conditions may have a solution close to the previous one. The same idea applies within repeated optimization and derivative calls. It is the iterative nature of PCG that makes a starting guess useful here. The paper’s contrast with Riccati recursion concerns this opportunity as well as the different organization of the work.
After solving the QP, DiffMPC has a proposed trajectory update. A local approximation can suggest a step that looks good in the QP yet makes the original nonlinear dynamics residual worse. The authors evaluate a merit function that accounts for both the original cost and the current violation of the dynamics.
φ(x, u) = Σₜ [cˣₜ(xₜ) + cᵘₜ(uₜ) + μ‖fₜ(xₜ₊₁, xₜ, uₜ)‖₁]
The function φ is the merit score. Here the dependence on θ is held fixed and suppressed. The multiplier μ is the penalty weight for violating the dynamics, and the subscript on the norm indicates the sum of the absolute residual components. The stage sum applies the action and dynamics terms where a transition exists. The cost at the end of the trajectory is a state cost.
D_μ = Σₜ [∇cˣₜ(xₜ)ᵀΔxₜ + ∇cᵘₜ(uₜ)ᵀΔuₜ − μ‖fₜ(xₜ₊₁, xₜ, uₜ)‖₁]
Here D_μ describes the merit change used in the line-search test. The increments Δxₜ and Δuₜ are the QP candidate minus the current iterate at time t. The first two terms measure the objective change along that direction to first order. The dynamics term accounts for the predicted reduction in violation. The paper sets μ using a quotient of the summed directional cost terms and the summed absolute violations weighted by the line-search parameter ρ, set to 0.5.
Δφ_α = φ(x + αΔx, u + αΔu) − φ(x, u) − ηαD_μ
In this equation α is a candidate SQP step size. The sequences Δx and Δu contain the stage increments. The quantity Δφ_α measures the candidate against the required decrease, with η set to 0.4 for this test. This η belongs to the line search and is distinct from the PCG residual product. The candidates are 1.0, 0.7, 0.3, 0.1, and 0.01. DiffMPC evaluates them in parallel, then selects the largest candidate whose test is negative. The algorithm initializes the choice to the smallest candidate, which is the fallback if the tests find no acceptable larger step. The selected update becomes the next trajectory guess.
Differentiate the solution
The backward pass begins with a loss on the solution. The loss might measure disagreement with an expert’s actions or the performance of a sequence of actions in simulation. A backward calculation must convert the derivative of that loss with respect to the solved trajectory into a derivative with respect to θ. DiffMPC does so by asking how the KKT conditions respond to a parameter change.
∂w/∂θ = −(∂F/∂w)⁻¹(∂F/∂θ)
Here w is the combined decision and multiplier vector, written as the pair z and λ. The residual F must vanish at the solution. Its derivative ∂F/∂w measures the change in the conditions when the solution changes, and ∂F/∂θ measures their direct change as a parameter varies with w held fixed. The negative sign expresses the compensation between these two changes. This application of the implicit function theorem requires an invertible local KKT matrix. The formula describes a local solution branch under the assumptions needed for that theorem.
The matrix ∂w/∂θ is a Jacobian, with one column for each parameter. Building the entire matrix would entail a linear solve for each such column. When training needs the gradient of a scalar loss, DiffMPC uses the derivative of that loss to select the relevant combination in advance. This is called a vector–Jacobian product.
[G Hᵀ; H 0] [z̃; λ̃] = [∂ℓ/∂z; 0]
The scalar training loss is ℓ. Its gradient ∂ℓ/∂z is the incoming derivative on the trajectory. The lower zero expresses that the training loss in this derivation has no direct argument for the KKT multipliers. The adjoint variables z̃ and λ̃ belong to the backward calculation. They encode how the incoming loss derivative propagates through the optimization conditions. The symmetry of the KKT matrix allows the same structured solve to handle the adjoint equations.
∇θℓ = −(∂F/∂θ)ᵀ[z̃; λ̃]
Here ∇θℓ is the part of the loss gradient flowing through the optimizer to θ. Multiplication by the transpose of ∂F/∂θ maps the backward solution into the parameter space. A cost parameter affects the cost-related conditions. A dynamics parameter can affect both the constraint residual and the stationarity condition that involves the dynamics derivatives. The computation can account for both paths.
The backward system reuses the forward matrix. The values on the right change, and the same Schur complement and preconditioner can be passed from the forward calculation to the backward one. As in the forward pass, a previous backward multiplier solution can be used as an initial guess. DiffMPC is implemented in JAX and the authors release the DiffMPC code.
There is an approximation in the matrix being reused. The exact KKT derivative of the nonlinear problem includes curvature from the dynamics constraints, weighted by the multipliers. In the paper’s compact notation for the objective and dynamics terms, that curvature has this form.
∇²z L = ∇²z c + ∇²z(λᵀf)
The operator ∇²z takes second derivatives with respect to the trajectory z. The scalar c is the full trajectory cost, and f in this display stands for the stacked equality residuals paired with λ. DiffMPC uses the cost curvature for its quadratic blocks and omits the second term. It also projects the cost blocks as described earlier. This choice avoids second derivatives of the dynamics and makes the matrix available for both passes. As the authors note, it can reduce gradient accuracy.
Where the data and rewards enter
Reinforcement learning and imitation learning use the same differentiation routine with different sources of the loss. In reinforcement learning, the paper uses closed-loop experience. An initial state is drawn, the policy plans from that state, an action is applied to the simulator, and the resulting state becomes the next planning input. The objective rewards the behavior over the episode.
max_θ E[Σ_{t=1}^{H} R(xₜ, πθ(xₜ))], xₜ₊₁ = SimEnv(xₜ, πθ(xₜ)), x₀ ∼ D_initial
Here H denotes episode length, separate from the matrix H used in the KKT system. The expectation E is over the sampled settings, and R is the reward for the state and chosen action. The symbol πθ denotes the policy parametrized by θ, and SimEnv is the environment’s simulated transition. The sampling symbol ∼ indicates that the initial state x₀ comes from the distribution D_initial. The episode can call the controller repeatedly, with each call solving its own prediction problem. The authors use differentiable simulation so gradients can also pass through the environment transitions in their reinforcement-learning experiments.
For imitation learning, the data already include actions to match. The authors train the controller to produce a plan close to the demonstrated plan from the same initial state.
min_θ E[‖(û₀, …, û_T) − πθ_{0:T}(x₀)‖²], (x₀, û₀, …, û_T) ∼ D_demonstrations
A hat marks an action from the demonstration. The policy with the horizon subscript denotes the sequence of actions produced by solving the optimal-control problem, using the paper’s action-sequence notation. The norm squared measures action discrepancy across that sequence. D_demonstrations is the distribution of starting states and demonstrated actions. The resulting loss sends a derivative directly into the predicted actions, after which the implicit backward pass determines how changing θ would affect the match.
Experiments and results
Batched reinforcement learning with affine dynamics
The main timing benchmark uses generated control problems with quadratic costs and affine dynamics. An affine transition predicts the next state using a linear combination of the current state and action plus a constant offset. The authors sample the dynamics matrices and initial states. They constrain the magnitudes of the state transition matrix’s eigenvalues to the interval ending at 0.99. The learned quantities are the diagonal state-cost weights. Actions contribute a squared-norm cost fixed for the benchmark.
xₜ₊₁ = Axₜ + Buₜ + b
In this experiment A maps the current state xₜ into the prediction, B maps the action uₜ, and b is the constant offset. The next state is xₜ₊₁. These are matrices and an offset for the generated benchmark environment, distinct from the time-indexed derivative blocks and stacked objective vector in the solver notation.
R(x, u) = −(‖x‖₂² + ‖u‖₂²)
The reward R is the negative sum of the squared Euclidean norms of the state x and action u. The subscript ₂ denotes the Euclidean norm. Maximizing the aggregate reward encourages both small states and small actions. The metric timed in the benchmark is the computation of that reward and its gradient with respect to the cost parameters.
The problem emphasized in the main timing figure is Problem 1. Its state dimension is 8, its action dimension is 4, and its prediction horizon is 40. An episode lasts 50 environment steps and a batch contains 64 randomized environments. The authors report averages over 10 seeds for each problem. Across the problem configurations they also vary the prediction horizon, the dimensions of the state and action, and the batch size. The other batch sizes include 16 and 256. For the gradient, the backward timing includes the forward evaluation needed to supply inputs to the backward computation.
The comparison uses DiffMPC and three baselines. Trajax is an iLQR solver implemented in JAX. The PyTorch library mpc.pytorch also uses iLQR. Theseus is a PyTorch-based nonlinear least-squares solver, so it computes the trajectory through a rollout inside its objective and uses damped least squares with dense Cholesky factorization. The experiment uses implicit differentiation and float64 calculations. Timings were collected on a workstation with an AMD Threadripper 3990X and an NVIDIA GeForce RTX 3090.
Because these optimization problems are already quadratic with affine constraints, the benchmark limits the outer solve to a single iteration. It also removes or restricts line-search work. Trajax uses a minimum line-search step of 0.99 because setting that minimum to 1 prevented acceptance in the authors’ setup. DiffMPC uses a single candidate of 1 in the timing benchmark. Its inner PCG solve still iterates and uses a tolerance of 10⁻¹². Thus the limit on outer iterations does not give each solver the same number or kind of internal operations. It establishes a common task for the structured and general-purpose approaches.
Mean GPU backward-pass time on reinforcement learning Problem 1
DiffMPC records the shortest time for computing the rollout and its gradient.
The numbers
| System or setting | s |
|---|---|
| Theseus | 6.19 |
| mpc.pytorch | 4.46 |
| Trajax | 1.83 |
| DiffMPC (this paper) | 0.32 |
The forward-only GPU timings on Problem 1 show the same ordering. Theseus takes 4.39 s, mpc.pytorch takes 1.91 s, Trajax takes 0.95 s, and DiffMPC takes 0.22 s. The paper describes the result on this problem as a 4 times speedup over the fastest baseline. The forward and backward means are separate measurements, and the backward measurement already includes a forward evaluation.
The CPU results give a different picture of the solver choices. On Problem 1, Trajax takes 0.93 s for the forward pass and 1.90 s for the backward measurement. DiffMPC takes 1.33 s and 2.70 s. Theseus takes 49.35 s on the CPU for the forward measurement and 81.47 s for the backward measurement. Its CPU runs also show much greater variation. On the GPU, the structural control solvers have a large advantage over Theseus on this benchmark, and DiffMPC makes the strongest use of that hardware.
The spread across configurations is relevant because a GPU needs enough useful work available at once. On Problem 2, which uses a batch size of 16, DiffMPC’s GPU forward mean is 0.11 s and Trajax’s is 0.70 s. On Problem 4, which uses a batch size of 256, the GPU forward means are 0.49 s and 1.93 s, respectively. These are distinct generated problem settings. They show that DiffMPC’s timing advantage appears at both tested batch sizes. The absolute times also show that larger batches increase the total workload, so the batch count on its own does not predict the shortest elapsed time.
Nonlinear attitude stabilization
The authors add a nonlinear experiment in which a controller applies torques to bring a rigid body’s rotation rates toward zero. Unlike the affine benchmark, the prediction includes a product of the rotational state with its angular momentum. The dynamics depend on the sampled inertia, so changing the initial rates or the inertia changes the control problem.
Jω̇ = Jω × ω + τ
The matrix J is the diagonal, positive definite inertia matrix. The vector ω contains the angular rates, and the dot marks their time derivative. The cross symbol × is the vector cross product. The vector τ is the applied torque. The authors use a forward Euler discretization, which advances the state using the derivative evaluated at the current state, with a step of 0.1 s.
The controller has a prediction horizon of 25. Its nominal state and action cost matrices are identities, and reinforcement learning adjusts their diagonal entries. The authors use a batch size of 16. They sample the initial angular-rate components from the uniform range [−1, 1] and the diagonal inertia entries from the uniform range [0.1, 10]. The training reward weights the squared angular-rate norm by 0.1 inside the negative sum of state and action penalties.
Mean backward-pass time on nonlinear attitude stabilization
DiffMPC takes less time than Trajax to compute the backward pass.
The numbers
| System or setting | ms |
|---|---|
| Trajax | 505.0 |
| DiffMPC (this paper) | 69.3 |
The forward computations take 310.6 ms for Trajax and 39.8 ms for DiffMPC. The paper describes the backward result as an roughly 7.3× speedup. This experiment extends the timing evidence to a nonlinear control task at a modest batch size. Like the affine benchmark, its main reported comparison is the time to compute the quantities used for training.
Imitation of a cart-pole expert
In the imitation experiment, the system is a cart carrying a hinged pole. Its state records cart position, cart velocity, pole angle, and pole angular velocity. A horizontal force is the action. The transition is nonlinear because the motion depends on the pole’s orientation as well as the applied force. The paper specifies a cart mass of 1, a pole mass of 0.1, a length of 0.5, and a gravitational constant of 9.81 for this benchmark.
The expert trajectories come from DiffMPC using fixed cost parameters. Its state-cost diagonal is (1, 2, 1.5, 1) and the action weight is 0.05. The authors draw 32 starting states. Cart position and velocity are sampled uniformly from [−0.5, 0.5], pole angle from [−π, π], and pole angular velocity from [−1, 1]. Each starting state contributes a trajectory from the expert controller. The learner begins with state-cost weights sampled uniformly from [0, 1] and tries to match the expert’s action sequences.
Training uses gradient descent on the mean squared action error, with a batch size of 32 and a learning rate of 10⁻². Both Trajax and DiffMPC start their solves from the expert trajectory. The paper limits their outer iLQR or SQP computation to five iterations. The comparison uses the same expert data, and the training loop encompasses solving the nonlinear problems, evaluating the imitation loss, computing gradients, and changing the learner’s weights.
The paper plots two kinds of error against measured training time over 200 epochs. The imitation loss measures disagreement in action space. The parameter error measures the distance between the recovered cost weights and the known weights used to generate the expert. They answer different questions. Matching the actions demonstrates agreement on the behavior presented in the data. Recovering the expert weights measures agreement about the cost parameters in this particular generated task.
parameter error = ‖θ − θ⋆‖₂
Here θ is the learner’s current vector of cost weights, θ⋆ denotes the known expert weights, and the Euclidean norm gives the size of their difference. The star indicates the data-generating parameters. It does not depend on comparing the learner’s actions with a separate physical expert.
DiffMPC runs the imitation-learning procedure roughly 2 times faster than Trajax on the GPU. The significance of this comparison lies in what the clock includes. A faster linear solver can make an individual optimization pass cheaper, whereas the imitation plot follows an entire repeated training loop and shows how the losses evolve in elapsed time.
Learning to handle a sudden loss of grip
The final application asks whether tuning through the controller can improve behavior when the real dynamics differ from the controller’s predictions. A car already operating near the tire forces available on a dry surface may have little room to correct its motion when it reaches water. The training setup makes that possibility recur by drawing different puddle conditions and initial positions. The objective encourages the car to retain a drift while tracking the reference path.
The paper uses a dynamic bicycle representation, with front and rear tire behavior combined into a vehicle prediction. The state includes yaw rate, longitudinal speed, sideslip angle, rear wheel speed, heading error, lateral tracking error, and distance along the reference. Sideslip measures the angle between the direction the car points and the direction in which it moves. Steering and engine torque determine the applied controls. The controller also penalizes changes in these controls, so the predicted trajectory reflects the cost of abrupt inputs as well as deviations from the reference.
The simulator includes a more accurate dynamics integrator than the controller uses for prediction. It accounts for control delays, actuator bounds, and the low-level interpolation used to select commands from the optimization plan. The MPC prediction uses a trapezoidal discretization at 0.1 sec. The training rollout advances in steps of 20ms and includes a 20 ms delay for incoming control. The optimizer uses a prediction horizon of 35 timesteps and performs a single SQP iteration per control update, matching the real-time iteration scheme used at deployment.
Domain randomization varies the environments in which the policy is evaluated during training. In addition to the initial position on the path, the authors vary the puddle length and the relative positions at which the front and rear wheels encounter water. This is pertinent when a car is traveling sideways and the wheels need not reach the disturbed surface in their usual order. The simulator represents a puddle by reducing the tire friction coefficient to 0.6. The controller optimizes using its own predictive parameters, which training is free to adjust.
Each batch contains 32 environments and each episode runs for 200 steps. Gradients propagate through the rollout returns to the controller parameters. The candidates for learning include the state and control-rate weights as well as the front and rear friction values, front and rear cornering stiffness, and rear-wheel inertia. Using an NVIDIA GeForce RTX 4090, the authors complete 1000 training steps in 14 hours. They run training on the figure-8 path only. In this experiment, robust training required episodes longer than 100 timesteps and batch sizes of at least 32, according to the authors’ observations.
Completion rate in randomized figure-8 drifting simulations
The learned controller completes every reported trial, while the dry-tuned baseline completes fewer.
The numbers
| System or setting | % |
|---|---|
| Manually tuned baseline | 70 |
| Learned DiffMPC controller (this paper) | 100 |
The comparison covers twenty simulated rollouts for the baseline and learned policies over randomized environments. The baseline uses weights designed by hand and tested under nominal dry conditions. The learned controller typically uses smaller steering angles and lower motor torques in the reported comparison. Its sideslip and wheel speeds are lower. The authors interpret this behavior as leaving more room for corrective control when available grip falls.
The hardware tests use the learned parameters on a Toyota Supra. The circular maneuver takes the controller to a reference path different from the one used for training. In the reported puddle comparison, the baseline spins out and the learned controller sustains a drift with less sideslip and lower torque. The appendix also reports a physical figure-8 comparison in which the learned controller completes the maneuver and the baseline spins out on the first turn. For that comparison, hardware constraints allowed only one run per method. The system on the car uses OSQP for its quadratic programs. DiffMPC provides the training computation that produces the parameters used in the hardware study.
What the ablations show
Warm starts help most at the looser tested tolerance
The warm-start comparison changes the starting point of the PCG iterations while keeping DiffMPC and the reinforcement-learning problem fixed. The cold condition starts with zero multipliers. The warm condition uses earlier multiplier solutions. The authors test tolerances of 10⁻⁴, 10⁻⁸, and 10⁻¹² on Problem 1 and collect statistics over 100 independent runs per tolerance. This experiment tests a specific feature of the method without changing the optimization formulation or comparing different implementations.
At 10⁻¹², the warm start gives a reported 4% speedup for the forward pass and 4% for the backward pass. At 10⁻⁴, the speedups are 11% and 9%, respectively. A plausible explanation follows directly from the stopping rule. When the tolerance permits a larger residual, a good initial guess can bring the system close enough to the stopping condition that fewer iterations are needed. An especially strict tolerance can require more work even after the initial residual has been reduced. The measured result concerns the benefit of warm-starting at each tolerance. The experiment does not report that every tolerance produces equally useful gradients during training.
The gain at the strict benchmark tolerance is also modest in relation to the reported cross-solver GPU timing gap. The comparison indicates that previous solutions can help, especially when approximate linear solves are acceptable. It gives little reason to attribute the full advantage to warm starts alone. The ability to expose simultaneous matrix operations across prediction time is a separate part of the design.
Hardware and problem size reveal where the solver benefits
Running the solvers on CPU and GPU changes the execution environment while retaining the benchmark tasks. The resulting rankings help distinguish the usefulness of the algorithmic structure from the advantage of executing that structure on a particular device. On Problem 1, a sequential-in-time baseline such as Trajax has similar forward means on CPU and GPU. DiffMPC gains considerably when it moves to the GPU. Trajax is faster than DiffMPC on the CPU for that problem. The result is consistent with the authors’ account that Riccati recursion makes efficient use of CPU execution and that DiffMPC’s local matrix operations offer more parallel work on a GPU.
The authors also test several configurations of the quadratic benchmark. Some comparisons hold the horizon and dimensions fixed and change the batch size. Others change the state and action dimensions. This is a small study of behavior under different workloads. It supports the claim that the GPU timing result is not confined to the single main example. It does not isolate a universal relationship between runtime and horizon length, dimension, or batch size. Those factors determine the work a solver must do, and each solver deals with that work through a different algorithm.
The change to mpc.pytorch is another targeted timing comparison. The authors remove a serial list comprehension that incurred overhead when inequality constraints were disabled and ensure the solver can exit after the first iteration while preserving the gradient path. For the first seed of Problem 1 on the GPU, they report a forward time of 67.9 s with the original code and 1.9 s with the modified setup. The backward time changes from 136.4 s to 4.5 s. This check shows why implementation choices matter in addition to the underlying numerical method. The main comparison uses the faster modified baseline.
Taken together, these tests support the explanation that performance depends on how work is organized. A baseline can benefit from removing serial implementation overhead. DiffMPC can benefit from reusing a starting point. The hardware comparison shows a larger gain for the implementation built to make operations across the time horizon available in parallel. A separate timing with the stair preconditioner removed would be needed to isolate how much of the gain comes from that component, and the reported comparisons do not supply one.
The driving analyses connect the learned parameters to behavior
The driving study compares the controller’s parameters before and after the full reinforcement-learning procedure. The rear friction coefficient in the controller’s prediction changes by -13%. The cost weight on sideslip tracking error changes by -58%. These are changes to separate parts of the optimization. The friction value influences predicted motion under a proposed action. The tracking weight influences how willing the optimizer is to accept a sideslip different from the reference.
Their combined effect is visible in the simulated trajectories and actions. The learned policy drifts with lower sideslip and wheel speed and uses smaller corrective demands in the reported trials. The authors explain that a lower assumed friction can lead to gentler plans under nominal conditions. A lower sideslip tracking cost can make those plans acceptable even when the reference calls for a larger drift angle. This explanation is consistent with the action traces and the improvement in completion rate. The study learns the weights and physical parameters jointly, so the evidence concerns the resulting policy as a whole. It does not assign an independent share of the improvement to each changed parameter.
There is a separate comparison concerning the training objective. The authors report that omitting the term rewarding sideslip leads to policies that follow the path robustly without drifting. The observation matters because completing the route and completing the intended maneuver are different outcomes. A controller that avoids the unstable regime entirely can succeed at path tracking. Including the sideslip incentive places the policy back in the regime the experiment is meant to study. The paper reports this as an observed change in behavior, without a numerical performance comparison for the reward variant.
The transfer to a circle examines a different part of the design. The learned policy retains a planning problem that takes a reference trajectory as input. When deployed on the circular reference, it can compute a new plan using the learned cost and dynamics parameters. That makes transfer possible without training on the circle. The study shows the transfer for the reported maneuver and setup. It leaves open how much of the effect depends on similarities between the training and transfer trajectories.
Limitations
Limits identified by the authors
DiffMPC directly formulates the control problem with equality constraints. The authors discuss putting additional inequalities into the cost as penalties or handling some control bounds through the dynamics. In the drifting experiment, the environment enforces actuator bounds while the controller’s optimization omits explicit box constraints. This allows experience with saturation to influence training. An explicit constraint in the optimizer would instead restrict which actions are permitted in each plan. The authors point to augmented Lagrangian and interior-point techniques as possible ways to improve constraint handling and convergence. They also note that a solution derivative can change discontinuously where an inequality becomes active or inactive.
The authors identify another tradeoff in their curvature approximation. They omit the dynamics contribution to the Lagrangian Hessian, which saves second-derivative work and simplifies reuse of the forward system. The derivative obtained from this matrix can be less accurate than one that includes those terms. The line search helps deal with the quality of an SQP step in the forward computation. It does not restore the curvature omitted from the backward equations. This matters when an application depends on accurate sensitivities, especially if constraints contribute substantially to the local curvature of the solution.
Initialization remains important. The paper notes that unfavorable guesses for the trajectory or the parameters can cause divergence and disrupt training. Warm-starting helps when a previous solution is an informative guess. Its benefit depends on similarity between the problems, and the warm-start experiment does not establish a general solution to poor initialization. The authors also report that the tool lacks explicit support for tuning solver settings such as iteration limits or PCG tolerance. These can affect the cost of each training update and the quality of the solved problem.
The CPU implementation is another boundary the authors identify. The JAX solver is designed around the opportunities available on the GPU. They expect a C or C++ implementation could reduce CPU overhead, while Riccati-based methods could still be faster on that hardware. The paper’s measured comparisons concern the implementations and configurations it tested.
Limits visible in the measurements
The headline timing comparison uses convex subproblems and deliberately restricts the outer iterations. That makes it easier to compare the cost of the forward and backward calculations. It supplies less evidence about difficult nonlinear problems that need repeated local approximations, have poor initial guesses, or encounter failing line searches. The attitude and cart-pole experiments extend the comparison beyond affine dynamics, with specific task setups and iteration choices. They provide examples of nonlinear workloads in which the approach helps.
Likewise, the reinforcement-learning timing experiments measure the cost of computing a reward and its gradient. They do not compare how much experience each solver needs to reach a target return on a broad suite of tasks. The cart-pole experiment offers a direct comparison of training time and error curves, with expert data produced by an optimizer in the same family as the learner. It therefore demonstrates parameter and action matching in a generated setting. Demonstrations from a controller outside that family, or from physical measurements with unknown expert costs, would pose a different estimation problem.
In the drifting study, robustness has a concrete meaning tied to the test conditions. The experiments involve sampled puddles and starting states in simulation and a small set of physical maneuvers. The simulator uses specified changes in friction, a particular delay, and actuator bounds. The higher simulated completion rate supports the learned controller’s performance under that randomization. It cannot establish a completion rate for arbitrary changes in road grip, different vehicles, or other maneuvers. Nor does the comparison isolate the contribution of every element of the training recipe, because the cost weights and dynamics parameters change together.
The authors explicitly caution against drawing strong conclusions from the single figure-8 hardware run per policy. The circular hardware result shows transfer to an untrained reference maneuver, and the physical implementation uses OSQP instead of DiffMPC’s PCG routine. These details define what the hardware result establishes. It tests the behavior of an MPC controller whose parameters were learned using DiffMPC. The GPU timing evidence and the physical deployment evidence concern different computations.
What came after
No later work is documented here that cites DiffMPC and shows how it extended or reused the method.
Cite
Cite as Emre Adabag, Marcus Greiff, John Subosits and Thomas Lew. 2025. Differentiable Model Predictive Control on the GPU. arXiv:2510.06179.
@misc{adabag2025differentiable,
title = {{Differentiable Model Predictive Control on the GPU}},
author = {Emre Adabag, Marcus Greiff, John Subosits and Thomas Lew},
year = {2025},
doi = {10.48550/arxiv.2510.06179},
eprint = {2510.06179},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.2510.06179}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/adabag-2025-differentiable-model-predictive-control-gpu/