MPC with a Differentiable Forward Model in JAX
Controlling a three-link robot arm by differentiating directly through Lagrangian dynamics with JAX.
Update: I revisited this post to replace the original 2023 code—which broke on multi-step rollouts due to a few subtle JAX and MPC bugs—with a clean, self-contained implementation verified against the course simulator. Near the end of the post, I walk through what went wrong in my first attempt and why.
In Columbia’s MECS6616 Robot Learning project, the goal is to swing a three-link planar robot arm from rest to a target point and bring its end-effector to a stop there. The standard approach in the course is Model Predictive Control (MPC) with constant-action shooting or numerical pseudo-gradients—simple, robust, and surprisingly effective.
Still, the assignment mentioned another possibility: if you have a differentiable forward model, you can optimize control inputs with exact analytical gradients instead of finite-difference perturbations. That made me curious. Could we rewrite the arm physics in JAX, differentiate straight through a multi-step rollout with jax.grad, and solve the reaching problem in ~100 lines of Python?
This post walks through that implementation, from the Lagrangian forward model to the JIT-compiled receding-horizon planner, along with the bugs that tripped me up the first time around.
Problem setup and MPC formulation
The setup follows the MECS6616 course simulator: a planar three-link arm attached to a fixed base at \((0, 0)\). Each link is a uniform rod of length \(\ell = 1\text{ m}\) and mass \(m = 0.1\text{ kg}\), subject to gravity (\(g = 9.8\text{ m/s}^2\)) and joint viscous friction (\(b = 0.1\)), integrated at \(\Delta t = 0.01\text{ s}\).
At \(t = 0\), the arm hangs straight down at rest with its tip at (0, −3). The target sits at (2.5, −0.7), roughly 3.40 m away from the starting tip and near the right edge of the arm’s 3 m reach. Simply applying torques that pull the tip toward the target is not enough: momentum will carry the arm right past it unless the controller plans ahead to brake.
Model Predictive Control handles this by turning control into repeated finite-horizon optimization. Given a discrete forward model \(x_{k+1} = f(x_k, u_k)\), at every replanning step we optimize a sequence of future torques \(U = (u_0, u_1, \dots, u_{H-1})\) over a lookahead horizon \(H\):
\[\min_{u_0, \dots, u_{H-1}} \; J(U; x_0) = \sum_{k=1}^{H} c(x_k, u_{k-1}) + c_F(x_H) \quad \text{s.t.} \quad x_{k} = f(x_{k-1}, u_{k-1}).\]We then apply only the first command \(u_0\) to the robot, observe the new state, shift the remaining plan forward as a warm start, and re-solve. With a differentiable \(f\) in JAX, computing \(\nabla_U J(U; x_0)\) reduces to automatic differentiation through the simulated rollout.
A compact differentiable forward model in JAX
State, kinematics, and tip velocity
The arm’s 6-dimensional state \(x = [q, \dot{q}]\) stores the three relative joint angles \(q \in \mathbb{R}^3\) followed by their angular velocities \(\dot{q} \in \mathbb{R}^3\). Because each angle is measured relative to the previous link, cumulative sums give the world-frame link orientations \(\theta_i = \sum_{j=1}^{i} q_j\) and angular velocities \(\omega_i = \sum_{j=1}^{i} \dot{q}_j\).
Each rod contributes a displacement \((\Delta x_i, \Delta y_i) = (\ell_i \cos\theta_i, \ell_i \sin\theta_i)\). Summing those vectors gives the tip position \(p\), and differentiating with respect to time gives the tip velocity \(v = (-\Delta y^\top \omega,\; \Delta x^\top \omega)\):
def tip(state):
q, dq = jnp.split(state, 2)
theta, omega = jnp.cumsum(q), jnp.cumsum(dq)
dx, dy = LENGTH * jnp.cos(theta), LENGTH * jnp.sin(theta)
return jnp.array([dx.sum(), dy.sum()]), jnp.array([-dy @ omega, dx @ omega])
Lagrangian dynamics instead of constraint matrices
The course simulator (ArmDynamicsTeacher) computes accelerations by assembling a \(15 \times 15\) Newton–Euler linear system that solves jointly for every link’s internal reaction forces, linear accelerations, and angular accelerations. Porting that matrix assembly line-by-line into JAX is verbose and easy to get wrong.
Instead, we can eliminate the internal constraint forces analytically using the Euler–Lagrange equations in absolute link angles \(\theta\):
\[M(\theta)\,\dot{\omega} + C(\theta, \omega) + g(\theta) = \tau_{\text{link}}.\]Let \(L\) be the \(3 \times 3\) lower-triangular matrix whose row \(i\) records the distance along each link \(j\) leading to the center of mass of rod \(i\) (\(\ell_j\) for \(j < i\), \(\tfrac{1}{2}\ell_i\) for \(j = i\), and \(0\) otherwise). From \(L\), we precompute a constant symmetric inertia matrix \(A = L^\top \operatorname{diag}(m)\, L + \operatorname{diag}\!\left(\tfrac{1}{12} m_i \ell_i^2\right)\) and gravity moment arms \(g\,(m^\top L)\) once up front:
# Row i gives the distances along each link to the center of mass of rod i.
lever = (jnp.tril(jnp.ones((3, 3)), -1) + 0.5 * jnp.eye(3)) * LENGTH
inertia = lever.T @ (MASS[:, None] * lever) + jnp.diag(MASS * LENGTH**2 / 12)
gravity_arm = GRAVITY * (MASS @ lever)
In absolute angles, the dynamics simplify nicely: the mass matrix is \(M_{ij}(\theta) = A_{ij}\cos(\theta_i - \theta_j)\), and the velocity cross-terms cancel out, leaving pure centrifugal coupling \(\bigl[C(\theta, \omega)\bigr]_i = \sum_j A_{ij}\sin(\theta_i - \theta_j)\,\omega_j^2\) plus gravity \(g_i(\theta) = g\,(m^\top L)_i\cos\theta_i\). Because joint \(i\) exerts \(+\tau_i\) on link \(i\) and \(-\tau_i\) on link \(i - 1\), the net torque on link \(i\)—including the simulator’s viscous damping term—is \(\tau_{\text{link}, i} = \tau_i - \tau_{i+1} - b\,\dot{q}_i\) (with \(\tau_4 = 0\)).
Solving this \(3 \times 3\) system yields the absolute angular accelerations \(\alpha = \dot{\omega}\). Taking adjacent differences converts back to relative joint accelerations \(\ddot{q}\), which we integrate with the course simulator’s trapezoidal-position update:
def step(state, torque):
q, dq = jnp.split(state, 2)
theta, omega = jnp.cumsum(q), jnp.cumsum(dq)
delta = theta[:, None] - theta[None, :]
mass_matrix = inertia * jnp.cos(delta)
bias = (inertia * jnp.sin(delta)) @ omega**2 + gravity_arm * jnp.cos(theta)
link_torque = torque - jnp.append(torque[1:], 0.) - FRICTION * dq
alpha = jnp.linalg.solve(mass_matrix, link_torque - bias)
ddq = jnp.diff(alpha, prepend=0.)
return jnp.concatenate((q + DT * dq + 0.5 * DT**2 * ddq, dq + DT * ddq))
In 10 lines of pure JAX, step is completely free of NumPy side effects, compiles cleanly with XLA, and reproduces the 150-line Newton–Euler course simulator to machine precision.
Differentiating through a multi-step rollout
The controller chooses a new torque vector every 0.1 s and holds it constant for HOLD = 10 simulation steps. A candidate plan therefore has shape (5, 3): five consecutive 0.1 s torque blocks, giving the controller a 0.5 s lookahead window to both accelerate toward the goal and decelerate before overshooting.
At the end of each 0.1 s block, we measure the squared distance to the target \(e_k^2 = \|p_k - p_{\text{goal}}\|_2^2\) and the squared tip speed \(s_k^2 = \|v_k\|_2^2\). The rollout cost averages both across the horizon, puts extra weight on the terminal position and speed so the arm commits to stopping, and adds a small torque penalty:
\[J(U; x_0) = \frac{1}{H}\sum_{k=1}^{H}\bigl(e_k^2 + 0.03\,s_k^2\bigr) + 2\,e_H^2 + 0.2\,s_H^2 + \frac{0.001}{3H}\sum_{k=0}^{H-1}\|u_k\|_2^2.\]In JAX, jax.lax.fori_loop handles the 10-step zero-order hold, and jax.lax.scan unrolls the 5-block horizon:
def hold(state, torque):
return jax.lax.fori_loop(0, HOLD, lambda _, x: step(x, torque), state)
def loss(plan, state, goal):
def block(x, u):
x = hold(x, u)
position, velocity = tip(x)
return x, (jnp.sum((position - goal)**2), velocity @ velocity)
_, (error2, speed2) = jax.lax.scan(block, state, plan)
return (jnp.mean(error2 + 0.03 * speed2) + 2 * error2[-1]
+ 0.2 * speed2[-1] + 0.001 * jnp.mean(plan**2))
The key detail is that x is threaded through jax.lax.scan as the loop carry: the output state of block \(k\) feeds directly into block \(k + 1\). When JAX differentiates loss with respect to plan, reverse-mode autodiff automatically backpropagates through the entire 50-step physics rollout, so the gradient for plan[0] captures its downstream effect on every future state in the horizon.
JIT-compiled optimization and receding-horizon control
Because loss is pure JAX, we can compile the entire inner optimization loop—not just a single gradient evaluation—into one XLA kernel. At each replanning step, optimize runs 30 iterations of projected Adam (lr = 0.12), clips each joint torque to \([-6, 6]\text{ N}\cdot\text{m}\), and keeps the lowest-cost plan encountered along the way:
@jax.jit
def optimize(plan, state, goal):
def update(i, carry):
u, first, second, best, best_cost = carry
cost, grad = jax.value_and_grad(loss)(u, state, goal)
best = jnp.where(cost < best_cost, u, best)
best_cost = jnp.minimum(cost, best_cost)
first = 0.9 * first + 0.1 * grad
second = 0.999 * second + 0.001 * grad**2
direction = (first / (1 - 0.9**(i + 1))) / (
jnp.sqrt(second / (1 - 0.999**(i + 1))) + 1e-8)
u = jnp.clip(u - LEARNING_RATE * direction, -TORQUE_LIMIT, TORQUE_LIMIT)
return u, first, second, best, best_cost
zeros = jnp.zeros_like(plan)
initial = (plan, zeros, zeros, plan, jnp.inf)
last, _, _, best, best_cost = jax.lax.fori_loop(0, ITERATIONS, update, initial)
return jnp.where(loss(last, state, goal) < best_cost, last, best)
In the outer receding-horizon loop, we execute only plan[0] on the arm, then shift the remaining four commands forward—repeating the last row to fill the fifth slot—to warm-start the next optimization:
for k in range(1, 51):
plan = optimize(plan, state, GOAL)
state = advance(state, plan[0])
plan = jnp.concatenate((plan[1:], plan[-1:]))
Here advance = jax.jit(hold). After the one-time JIT compilation (~0.8 s on CPU), all 50 replanning steps of the 5-second rollout execute in under a second.
Results and verification
Starting from rest, the planner immediately whips the arm upward—peaking at nearly 7 m/s at 0.2 s—and then brakes hard as the 0.5 s lookahead sees the target approaching. By 1 s, the tip is already within 6 cm of the goal; from 1.5 s onward, it hovers within 1–3.7 cm of the target, comfortably inside the course’s full-credit criteria (distance under 0.10 m and speed under 0.50 m/s at 5 s):
| Simulated time | Distance to target | Tip speed |
|---|---|---|
| 0 s | 3.3971 m | 0.0000 m/s |
| 1 s | 0.0604 m | 0.3715 m/s |
| 2 s | 0.0358 m | 0.1206 m/s |
| 3 s | 0.0128 m | 0.0067 m/s |
| 4 s | 0.0071 m | 0.0928 m/s |
| 5 s | 0.0172 m | 0.1306 m/s |
Notice the small residual micro-oscillation between 3 s and 5 s (speed creeping back from 0.007 m/s to 0.13 m/s). That comes from re-running fixed-step Adam (lr = 0.12) from fresh momentum buffers at every replanning tick: once the arm is already sitting on the target, a fixed step size slightly overshoots the exact gravity-compensation torques. Adding a learning-rate decay or switching to a second-order solver like L-BFGS or iLQR would damp out that last bit of chatter.
To make sure the JAX rewrite wasn’t silently diverging from the course physics or computing bogus gradients, I ran three checks (with jax_enable_x64 = True):
- Dynamics parity: Across 100 random state–torque pairs, the worst single-step state discrepancy between
stepandArmDynamicsTeacher.advancewas \(1.6 \times 10^{-14}\). - Gradient accuracy: Perturbing each of the 15 torques in a candidate plan by \(\pm 10^{-5}\text{ N}\cdot\text{m}\) matched
jax.grad(loss)to within \(3.3 \times 10^{-9}\). - Cross-simulator closed loop: Feeding the JAX planner’s commands into the original NumPy
ArmDynamicsTeachersimulator instead ofadvanceproduced virtually identical tracking—final distance 0.0173 m and tip speed 0.1290 m/s.
Run it yourself
The complete, self-contained script is available here: Download arm_mpc.py. It requires only JAX (tested on CPU with Python 3.10, jax[cpu]==0.4.38, and numpy==1.26.4):
pip install "jax[cpu]"
python arm_mpc.py
Running it prints the 1-second checkpoints shown in the table above.
What went wrong in the original 2023 version
When I came back to this post and actually stress-tested my 2023 code, it failed for three distinct reasons—all of which turn out to be classic traps when implementing differentiable MPC in JAX:
- Breaking the chain rule across time. My original
_planningloop steppedstate = dynamics.dynamics_step(state, action, dt)forward and summedjax.grad(calc_dist)(action, dynamics, state, goal, dt)at each intermediate step. That treated every intermediate state as a fixed constant, summing only one-step sensitivities while throwing away how an earlier torque shifts future states. Wrapping the rollout insidejax.lax.scankeeps the entire trajectory on the autodiff tape so gradients flow backward through time. - Mixing NumPy with JAX—and an ignored
.at[].set(). Because the old dynamics class built its constraint matrices with NumPy arrays and converted them to JAX only at the end, differentiating past a single step crashed as soon as a JAX tracer touched a NumPy array. On top of that, a subtle JAX immutability bug lurked in the torque difference: callingtau_shift.at[-1].set(0.)without reassigning the result discarded the zeroed entry, silently wrapping the base joint’s torque onto the last link. Writing the dynamics in pure JAX and usingjnp.append(torque[1:], 0.)eliminated both issues. - No lookahead to brake, and no speed penalty. Optimizing a single constant torque over 0.1 s with one raw gradient step and a distance-only loss gave the arm no way to plan deceleration—it could only pull harder toward the target until it flew past. Expanding the plan to five 0.1 s blocks and penalizing tip velocity—especially at the end of the horizon—is what lets the controller swing up quickly and settle cleanly.
Closing thoughts
Once the physics are written cleanly in JAX, differentiating through a smooth forward model is remarkably compact and fast: 108 lines of code, zero external optimization libraries, and sub-second replanning on CPU.
At the same time, revisiting this problem reinforced an intuition from my original post: analytical gradients are not automatically a silver bullet for control. Even on a smooth 3-link arm, first-order trajectory optimization still needs careful horizon design, torque bounds, and step-size tuning—and once you add longer horizons, non-convex obstacles, or discontinuous contacts, gradients can vanish, explode, or stop existing altogether. That is why sampling-based methods like CEM, MPPI, and evolution strategies remain hard to beat in messy robotics and RL settings, and why differentiable simulation shines brightest when paired thoughtfully with the structure of the dynamics.