Learn RL by playing with it.
An interactive companion to Reinforcement Learning: An Introduction by Sutton & Barto. Every chapter has a short summary, the key equations, a pointer to the book, live simulations you can poke at, and a quiz. Mark chapters as studied and your progress is saved in this browser.
Then an advanced track takes it to real robots: PPO, SAC and world models, sim-to-real, humanoids, residual RL on a Franka arm running live in MuJoCo, offline and real-world RL, safety and edge deployment. Same format: maths, something to play with, a quiz.
The Reinforcement Learning Problem
An agent interacts with an environment. At each step it sees a state, takes an action, and receives a scalar reward. Nobody tells it which action was right. It has to discover, by trial and error, behaviour that maximizes reward in the long run, which means trading off exploration against exploitation.
The agent–environment loop Fig. 3.1
The agent's goal is to maximize the expected return, the (discounted) sum of future rewards. That is the reward hypothesis.
Four elements of RL Sec. 1.3 — click to flip
🧠 Quiz
Finite Markov Decision Processes
An MDP formalizes the full RL problem. The dynamics \(p(s',r\mid s,a)\) give the probability of each next state and reward, and the Markov property says that the current state captures everything relevant from the past. The agent wants to maximize the expected return \(G_t\). Value functions tell us how good states and actions are, and the Bellman equations express them recursively.
\(G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots = R_{t+1} + \gamma G_{t+1}\)
\(v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s]\)
\(q_\pi(s,a) = \mathbb{E}_\pi[G_t \mid S_t = s, A_t = a]\)
The Bellman equations
The value of a state equals the expected immediate reward plus the discounted value of where you land. The equation for \(v_\pi\) is linear; the optimality equation has a max, which makes it nonlinear.
🧠 Quiz
Dynamic Programming
If you know the model \(p(s',r\mid s,a)\), you can compute optimal policies by turning the Bellman equations into update rules. Policy evaluation computes \(v_\pi\), policy improvement acts greedily with respect to it, and alternating the two gives policy iteration. Value iteration folds them into a single max-backup. The pattern where evaluation and improvement push each other toward optimality is called Generalized Policy Iteration (GPI), and it underlies everything that follows.
\(v_{k+1}(s) = \sum_a \pi(a|s) \sum_{s',r} p(s',r|s,a)[r + \gamma v_k(s')]\)
\(\pi'(s) = \arg\max_a \sum_{s',r} p(s',r|s,a)[r + \gamma v_\pi(s')]\)
\(v_{k+1}(s) = \max_a \sum_{s',r} p(s',r|s,a)[r + \gamma v_k(s')]\)
🧠 Quiz
Monte Carlo Methods
You don't need a model: just average the returns you actually observe. MC methods learn from complete episodes and don't bootstrap. Each state's estimate is independent of the others, which is good when the model is unknown but slow when episodes are long. Control follows GPI, using either exploring starts or ε-soft policies to keep exploring. Off-policy learning uses importance sampling to learn about one policy from data generated by another.
\(V(S_t) \leftarrow \text{average}(\text{Returns}(S_t))\), or with a constant step size: \(V(S_t) \leftarrow V(S_t) + \alpha[G_t - V(S_t)]\)
\(\rho_{t:T-1} = \prod_{k=t}^{T-1} \frac{\pi(A_k|S_k)}{b(A_k|S_k)}\)
\(V(s) = \frac{\sum \rho\, G}{|\mathcal{T}(s)|}\) vs \(V(s) = \frac{\sum \rho\, G}{\sum \rho}\)
🧠 Quiz
Temporal-Difference Learning
"If one had to identify one idea as central and novel to reinforcement learning, it would undoubtedly be temporal-difference learning." TD combines MC's sampling (no model needed) with DP's bootstrapping (update from other estimates). It learns online, after every step, from incomplete episodes.
\(V(S_t) \leftarrow V(S_t) + \alpha\big[\underbrace{R_{t+1} + \gamma V(S_{t+1}) - V(S_t)}_{\delta_t \text{ (TD error)}}\big]\)
\(Q(S,A) \leftarrow Q(S,A) + \alpha[R + \gamma Q(S',A') - Q(S,A)]\)
\(Q(S,A) \leftarrow Q(S,A) + \alpha[R + \gamma \max_a Q(S',a) - Q(S,A)]\)
Backup diagrams: DP vs MC vs TD
| needs model? | bootstraps? | samples? | online / incomplete episodes? | |
|---|---|---|---|---|
| Dynamic Programming | yes | yes | no | — (sweeps) |
| Monte Carlo | no | no | yes | no |
| Temporal-Difference | no | yes | yes | yes |
🧠 Quiz
Function Approximation
Real problems have far too many states for a table. Instead we learn a parameterized \(\hat v(s,\mathbf w)\) with far fewer weights than states, so an update to one state generalizes to others. We minimize the μ-weighted value error with stochastic gradient descent. With bootstrapped targets, the update is only a semi-gradient. For linear methods, feature construction (aggregation, polynomials, Fourier, tile coding) is where the craft lies.
\(\overline{VE}(\mathbf w) = \sum_s \mu(s)\,[v_\pi(s) - \hat v(s,\mathbf w)]^2\)
\(\mathbf w \leftarrow \mathbf w + \alpha\,[U_t - \hat v(S_t,\mathbf w)]\,\nabla \hat v(S_t,\mathbf w)\)
\(U_t = G_t\) (MC) or \(R_{t+1} + \gamma\hat v(S_{t+1},\mathbf w)\) (TD)
\(\hat v(s,\mathbf w) = \mathbf w^\top \mathbf x(s)\), \(\nabla\hat v = \mathbf x(s)\). TD converges to the TD fixed point, with \(\overline{VE}(\mathbf w_{TD}) \le \frac{1}{1-\gamma}\min_{\mathbf w}\overline{VE}(\mathbf w)\)
🧠 Quiz
Policy Gradient Methods
Instead of learning values and acting greedily, parameterize the policy directly as \(\pi(a\mid s,\boldsymbol\theta)\) and do gradient ascent on performance \(J(\boldsymbol\theta)\). Policies can become arbitrarily stochastic, handle continuous actions naturally, and change smoothly. The policy gradient theorem gives a gradient that does not require differentiating the state distribution.
\(\nabla J(\boldsymbol\theta) \propto \sum_s \mu(s) \sum_a q_\pi(s,a)\,\nabla \pi(a\mid s,\boldsymbol\theta)\)
\(\boldsymbol\theta \leftarrow \boldsymbol\theta + \alpha\,\gamma^t\,\big(G_t - b(S_t)\big)\,\nabla \ln \pi(A_t\mid S_t,\boldsymbol\theta)\)
\(\delta = R + \gamma \hat v(S',\mathbf w) - \hat v(S,\mathbf w)\)
\(\boldsymbol\theta \leftarrow \boldsymbol\theta + \alpha\,\delta\,\nabla \ln\pi(A\mid S,\boldsymbol\theta)\)
🧠 Quiz
Fundamentals, with a robot in the loop
The tabular chapters cover the ideas. This part revisits six of them with the questions a real robot raises: which value function do you actually need, whose data can you learn from, how do you explore without breaking a gearbox, what reward do you write, how do you get out of simulation, and why copying an expert isn't enough.
1Bellman, V vs Q, and the advantage
V scores a state, Q scores a state and a first action. Both average over everything the policy does afterwards:
They are tied together by two one-line identities. Chain them and you get the Bellman equations from Chapter 3:
\(Q^\pi(s,a)=\mathbb E\big[R+\gamma V^\pi(S')\mid s,a\big]\)
\(V^\pi(s)=\sum_a\pi(a\mid s)\,Q^\pi(s,a)\)
\(Q^*(s,a)=\mathbb E\big[R+\gamma\max_{a'}Q^*(S',a')\big]\)
Why Q matters for control. With Q you act by \(\arg\max_a Q(s,a)\), no model needed. With only V you have to look one step ahead, \(\arg\max_a\sum_{s'}p(s'\mid s,a)\,[r+\gamma V(s')]\), which needs the dynamics \(p\). That is the whole reason model-free control learns Q.
The advantage \(A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s)\) says how much better an action is than the policy's average. By construction it averages to zero under the policy, \(\sum_a\pi(a\mid s)A^\pi(s,a)=0\). That is exactly what makes it a good learning signal: it is the Q-value with the state's baseline subtracted, so policy gradients use it to push good actions up and bad ones down without the noise of "this state was good anyway".
2On-policy vs off-policy
An on-policy method learns only from data the current policy collected; after each update, the old batch describes a policy that no longer exists and is thrown away. An off-policy method learns from any transitions, kept in a replay buffer.
You can reuse old data with importance sampling, which reweights samples from the old policy to estimate an expectation under the new one:
This is exact in expectation, but as the policies drift apart a handful of samples get huge weights and the effective sample size collapses. PPO is on-policy for exactly this reason: its ratio \(r=\pi_\theta/\pi_{\theta_\text{old}}\) is only trustworthy near 1, and the clip to \([1-\epsilon,1+\epsilon]\) keeps it there. SAC and MPO sidestep the ratio. They learn a Q-function with Bellman backups, \(Q(s,a)\leftarrow r+\gamma\,\mathbb E_{a'\sim\pi}Q(s',a')\), and that target is valid for any stored transition \((s,a,r,s')\), whoever collected it.
Stable and simple, but sample-hungry. Fine when a GPU simulator hands you millions of steps an hour.
Reuses every transition, so far more sample-efficient, but bootstrapping on stale data is less stable. The usual choice on real hardware.
3Exploration vs exploitation, for a body
The trade-off is the bandit one from Chapter 2: exploit the best-known action, or try others and learn. What changes on a robot is that actions are continuous, the system has inertia, and the hardware has opinions. The usual tools:
\(a=\mu_\theta(s)+\sigma\,\xi\), with \(\xi\sim\mathcal N(0,I)\). The continuous cousin of ε-greedy.
\(J=\mathbb E\big[\sum_t r_t+\alpha\,\mathcal H(\pi(\cdot\mid s_t))\big]\). Exploration becomes part of the objective (SAC).
\(r_t+\beta\,\lVert\hat f(s_t,a_t)-s_{t+1}\rVert^2\). Bonus for surprise or novelty (curiosity, RND).
Independent Gaussian noise at 50 Hz mostly cancels itself out: the arm buzzes in place, wears the gears and goes nowhere. Temporally correlated noise such as an Ornstein–Uhlenbeck process explores much further for the same per-step spread. Simple action smoothing mostly buys gentleness: it cuts the action rate by an order of magnitude, at some cost in reach.
Other structured options: demonstrations to start near something sensible, initialising from a BC policy, auxiliary tasks (SAC-X), and keeping exploration inside safe joint and torque limits.
4Reward shaping and sparse rewards
A sparse reward, 1 on success and 0 otherwise, says exactly what you want but gives almost no signal until the agent stumbles on success by chance. A dense, shaped reward learns faster, but any loophole will be found: that is reward hacking.
Potential-based shaping (Ng, Harada & Russell, 1999) is the one kind of shaping that is guaranteed safe. Pick any potential \(\Phi(s)\) over states and add
The sum telescopes. Every return from \(s_0\) shifts by the same \(-\Phi(s_0)\) (taking \(\Phi=0\) at terminal states), so \(Q'(s,a)=Q(s,a)-\Phi(s)\) and the argmax, the optimal policy, cannot change. In tabular Q-learning, shaping with Φ is the same as initialising Q to Φ (Wiewiora, 2003), so the best potential is your best guess of the optimal value. Here that is \(\Phi(s)=\gamma^{d(s)}\), where \(d\) is the walking distance to the goal. A plain "bonus for being close" has no such guarantee: hovering next to the goal forever earns \(b/(1-\gamma)\), which can beat finishing.
Other fixes for sparse rewards: Hindsight Experience Replay (relabel a failed episode as a success for the goal it actually reached), demonstrations, curricula and auxiliary tasks. On humanoids the reward is a long sum of hand-tuned terms (velocity tracking, energy, action rate, feet air-time, contact penalties), and tuning those weights is a large part of the job.
5Sim-to-real
A policy trained in simulation meets a robot whose masses, friction, motor strength and delays are all a bit different. Two complementary tools:
Fit the simulator's parameters to real data, \(\hat\xi=\arg\min_\xi\sum_t\lVert s^\text{real}_{t+1}-f_\text{sim}(s_t,a_t;\xi)\rVert^2\). Shrinks the gap itself.
Train on a distribution, \(\max_\theta\,\mathbb E_{\xi\sim p(\xi)}\big[J(\pi_\theta;\xi)\big]\). The policy becomes robust across the range, and you hope reality is inside it.
The rule of thumb: system ID narrows the gap, randomisation covers what remains. Randomise mass, friction, motor strength, sensor noise, terrain, external pushes and above all latency, which is often the single biggest gap. Beyond that:
- Actuator networks (Hwangbo et al., 2019, ANYmal): learn the motor's torque response from real logs and put that network inside the simulator.
- Online adaptation (RMA): an encoder turns the last few seconds of observations into a latent estimate \(z_t\approx g(\xi)\) of the hidden parameters, and the policy conditions on it.
- Delta-action models (ASAP, 2025): collect real data, learn the residual \(\Delta a\) that makes the simulator match reality, then fine-tune in that corrected simulator.
6Why behaviour cloning fails, and what fixes it
Behaviour cloning is supervised learning on the expert's state–action pairs, \(\min_\theta\,\mathbb E_{s\sim d_{\pi^*}}\big[\ell(\pi_\theta(s),\pi^*(s))\big]\). The catch is in the subscript: it is trained on states the expert visits, then tested on states it visits. A small mistake moves it somewhere the expert never went, where its mistakes are bigger, which moves it further away. If it errs with probability ε per step, the expected cost over horizon T can grow like
Roll out the learner, ask the expert what it would have done on the states the learner visited, add those labels, retrain (Ross et al., 2011).
Perturb the expert while recording (DART), so the data already contains recoveries from small mistakes.
Optimises on its own state distribution with a reward, so recovery is learned. And unlike BC, it can exceed the demonstrator.
🧠 Quiz
The deep RL workhorses
Three families do almost all of the work in robot learning today. PPO is the on-policy default when a GPU simulator gives you unlimited data. SAC and MPO are the off-policy choices when every sample costs wall-clock time on hardware. Model-based methods (Dreamer, TD-MPC2) learn a model of the world and plan or practise inside it.
7PPO internals: clipping, GAE, and why it rules robotics
Vanilla policy gradient takes one step per batch, then throws the batch away. PPO wants several epochs of minibatch updates on the same data, which means estimating the new policy's performance from the old policy's samples. Importance sampling gives the surrogate objective:
Maximised freely, that objective is happy to put all the probability on the single luckiest sample. PPO's fix is to take the more pessimistic of the plain and the clipped term:
Read it case by case. If \(\hat A_t>0\), increasing \(r_t\) pays off only up to \(1+\epsilon\); beyond that the gradient is zero, so there is no reason to push further. If \(\hat A_t<0\), the same happens below \(1-\epsilon\). The min means the clip only ever removes incentives, never adds them. The full loss adds a value loss and an entropy bonus, \(L=L^{\text{CLIP}}-c_1\,(V_\phi(s_t)-\hat V^{\text{targ}}_t)^2+c_2\,\mathcal H[\pi_\theta(\cdot\mid s_t)]\).
Generalised Advantage Estimation builds \(\hat A_t\) from TD errors, mixing short and long look-aheads with one knob \(\lambda\):
\(\lambda=0\) gives the one-step TD error: low variance, but as biased as the critic. \(\lambda=1\) gives \(G_t-V(s_t)\): unbiased, but it carries the noise of every future reward. Robotics codebases almost always sit at \(\lambda\approx0.95\).
Per minibatch, \(\hat A\leftarrow(\hat A-\mu)/\sigma\). Keeps the step size meaningful as rewards change scale.
rsl_rl watches the KL after each update: above \(2\times\) target it divides the rate by 1.5, below half the target it multiplies by 1.5.
With thousands of simulated robots on one GPU, samples are nearly free. Stability and simplicity matter more than sample efficiency, which is exactly PPO's trade.
8SAC and MPO: maximum entropy and KL-regularised RL
Soft Actor-Critic changes the objective itself. The agent is paid for reward and for staying random:
This gives soft versions of the Bellman equations. Their optimal policy is a Boltzmann distribution over Q, so the temperature α decides how greedy it is:
Learn \(Q_1,Q_2\) and bootstrap from \(\min(Q_1,Q_2)\). A max over noisy estimates is biased upwards; the min cancels most of it.
Pick a target entropy \(\bar{\mathcal H}\) (often \(-\dim\mathcal A\)) and minimise \(\alpha\,(\mathcal H(\pi)-\bar{\mathcal H})\). If the policy gets too certain, α grows.
\(a=\tanh(\mu_\theta(s)+\sigma_\theta(s)\,\xi)\), so the actor gets gradients through \(Q(s,a)\) directly.
MPO (Maximum a-posteriori Policy Optimisation, from DeepMind's control group) reaches a similar place by an EM-style loop. It never follows a policy gradient: it builds a better policy non-parametrically, then fits the network to it.
The temperature η is not a hyperparameter here: it is solved for, via a convex dual, so that the E-step moves exactly as far as ε allows. Both SAC and MPO learn Q with Bellman backups, so both are off-policy and reuse a replay buffer, which is why they are the usual picks for learning on real robots.
9Model-based RL: Dreamer and TD-MPC2
Learn a model of the dynamics, then either plan with it or practise in it. Planning with a model usually means model-predictive control: optimise a short action sequence in imagination, execute only the first action, observe, and replan.
A recurrent world model in a learned latent space (RSSM). The actor and critic train entirely on imagined latent rollouts, using λ-returns, with robust tricks (symlog, return normalisation) that let one set of hyperparameters work across very different domains.
A latent model trained only to predict reward, value and the next latent (no pixel reconstruction), plus MPPI planning over a short horizon with a learned Q as the terminal value \(\hat V(\hat s_H)\). Strong on continuous control, scales to many tasks.
The upside is sample efficiency: every real transition trains a model that can generate many imagined ones. The downside is model exploitation. A planner is an optimiser, and it finds the places where the model is wrong in its favour. Fixes: keep collecting real data where the plans go, penalise model uncertainty (ensembles, MOPO), plan over short horizons, and let a learned value function handle everything past the horizon. The trend is towards world models as simulators, including video world models used to evaluate robot policies before they ever touch hardware.
🧠 Quiz
The robot RL pipeline, 2026 edition
A locomotion policy that walks on a real quadruped or humanoid is mostly the product of four engineering choices around a fairly plain PPO: simulate thousands of robots at once, train with information the real robot will never have, design the action space so the network has an easy job, and order the tasks so there is always something to learn.
10Massively parallel GPU simulation
The shift that made robot RL practical was moving the physics onto the GPU and running thousands of copies of the robot in one batched step. Observations, rewards and actions never leave the device, so the policy, the simulator and the PPO update all share the same tensors. On a single GPU a quadruped learns to walk on rough terrain in minutes to hours, not days.
Isaac Lab (on Isaac Sim), MuJoCo MJX and MuJoCo Playground, Genesis, and Newton (NVIDIA, Google DeepMind and Disney Research).
legged_gym + rsl_rl (ETH Zürich): the compact PPO most legged-robot work still starts from.
\(N_\text{env}\times T\) samples per iteration, e.g. \(4096\times24\approx98\text{k}\), so short rollouts per env are fine.
A GPU step costs a fixed launch overhead plus a per-environment cost, until the device is full. Throughput in environment steps per second is therefore
Short rollouts bring one subtlety. With \(T=24\) almost every rollout ends on a time limit, not a real terminal state, and the robot wasn't dead, just interrupted. Bootstrapping from 0 there would teach the critic that the world ends every 24 steps. The fix is to treat time-outs differently from failures:
11Asymmetric actor-critic and teacher–student distillation
In simulation you know everything: true base velocity, friction, contact states, terrain heights, motor strengths. On the robot you have joint encoders, an IMU and maybe a camera. Two standard ways to exploit the difference:
The critic sees privileged state, \(V_\phi(s^\text{priv}_t)\); the actor sees only what the robot will see, \(\pi_\theta(a_t\mid o_{t-k:t})\). Better value estimates mean better advantages. The critic is thrown away at deployment, so it may cheat.
Train a teacher \(\pi_T(a\mid s^\text{priv})\) with RL, then distil it into a student that sees only sensor history: \(\min_\psi\ \mathbb E_{o\sim d_{\pi_S}}\big\lVert\pi_S(o_{t-k:t})-\pi_T(s^\text{priv}_t)\big\rVert^2\), collected DAgger-style on the student's own states.
RMA (Rapid Motor Adaptation) makes the hidden part explicit. The teacher compresses environment parameters \(e_t\) (friction, payload, terrain) into a latent \(z_t=\mu(e_t)\); the student learns an adaptation module that recovers it from recent history, \(\hat z_t=\phi(o_{t-k:t},a_{t-k-1:t-1})\). That is system identification done implicitly, online, at 50 Hz. It is also why history length matters: a short window is noisy, a long one is slow to notice the ground has changed.
12Action space and control design
Almost every legged and humanoid policy outputs joint position targets, not torques. A PD loop on the motor driver turns them into torque at a much higher rate:
The policy runs at 50–100 Hz and the PD loop at 1 kHz or more, so the network only has to say where each joint should be, and the stiff, fast part is done in firmware. The gains set the joint's character. For a joint with inertia I, the closed loop is a spring and damper:
Stiff gains track well but amplify every jitter in the policy; soft gains are compliant and forgiving. The action scale s sets how far one unit of output moves a joint.
Feed the last few observations and actions back in. It handles partial observability and lets the policy model its own delay.
Penalise \(\lVert a_t-a_{t-1}\rVert^2\) and \(\lVert\ddot q\rVert^2\), or low-pass the actions. Jitter that is harmless in sim cooks real gearboxes.
13Curriculum learning
Start where the policy can sometimes succeed, and raise the difficulty (terrain roughness, stair height, command range, randomisation strength) as it gets better. Without that, a hard task gives no learning signal at all. A useful way to see why: if a batch of episodes succeeds with probability p, the information in their outcomes, and the variance that a policy gradient can exploit, is
The terrain game from legged_gym keeps every environment near that sweet spot automatically: each robot has a level; if it walks far enough it moves up a level, if it covers less than half the distance it moves down. Fancier automatic curricula pick tasks by measured learning progress (ALP-GMM, prioritised level replay), but the principle is the same: train where success is uncertain.
🧠 Quiz
Humanoids
A humanoid is the hardest place to write a reward by hand: "walk naturally" has no formula. The current recipe takes motion from people, teaches a fast low-level controller to track it, and puts a slower, smarter model on top to decide what to track. Then it tries to do all that while carrying something.
14Motion imitation from human data
The pipeline: capture human motion (mocap suits, or increasingly plain video with a pose estimator), retarget it to the robot's body (scale limbs, solve inverse kinematics so hands, feet and torso land where the human's did, respect joint limits), then train a policy with RL to reproduce it under real physics.
DeepMimic (Peng et al., 2018) makes the reward a product of tracking kernels. Every term is an exponential of a squared error, so the reward is in [0, 1], smooth, and informative even when the robot is far off:
Pose, velocity, end-effectors (hands and feet) and centre of mass, against the reference \(\hat{\cdot}\) at the current phase. Two training tricks matter as much as the reward: reference state initialisation (start episodes at random points along the clip, so the policy sees the hard middle of a backflip and not just the start) and early termination (stop when the torso touches the ground, so the policy doesn't learn to flail on the floor).
AMP (Adversarial Motion Priors, Peng et al., 2021) drops the explicit tracking. A discriminator learns to tell dataset transitions \((s,s')\) from the policy's, and its output becomes a style reward added to whatever task reward you like:
The policy no longer has to follow one clip frame by frame; it only has to move in a way the discriminator can't tell from the data. The cost is everything that makes GANs hard: an unstable game, and mode collapse onto one style. Today's humanoid work mostly tracks: H2O and OmniH2O, HumanPlus, ExBody, BeyondMimic, and general motion trackers trained on thousands of clips (e.g. AMASS) so one policy can follow almost any human motion it is given.
15Whole-body control as the layer under a VLA
A vision-language-action model is good at deciding what to do and too slow and too far from the physics to keep a humanoid upright. The working split is a hierarchy:
1–10 Hz, sometimes slower. Reads cameras and language; outputs targets: end-effector poses, base velocity, keypoints, often as a chunk of future targets.
50 Hz policy over a 1 kHz PD loop. Trained in simulation to track arbitrary commands \(g\) while balancing: \(\pi_\text{low}(a\mid o_{t-k:t},g_t)\).
Examples: HOVER trains one controller with a masked, multi-mode command interface (track joint angles, or root velocity, or hand keypoints, or any mix), and NVIDIA's GR00T stack puts a learned whole-body controller under the VLA. Why the split is forced becomes obvious from the simplest balance model, the linear inverted pendulum. With the centre of mass at height z and the zero-moment point p (where the ground reaction acts, inside the foot):
The system is unstable with a time constant \(1/\omega\approx0.3\) s: any error doubles in about 0.2 s. A controller that only updates every 300 ms, or sees the state 100 ms late, is always correcting a fall that has already grown. A fast controller that keeps the capture point \(\xi\) where it should be can hold balance easily, and then it doesn't matter much how slowly the target changes.
16Loco-manipulation
Walking while carrying a box, opening a door, or pushing a cart couples the two halves of the body: every force the arms apply, and every kilogram they hold away from the body, moves the centre of mass and the zero-moment point the legs must keep inside the feet:
The hard parts are the coupled dynamics, contact-rich interaction (the box can slip, the door pushes back), and the size of the problem: a full humanoid has 30-odd actuated joints and an observation that now includes the object. Two designs are common. A unified whole-body policy learns everything at once and can discover coordinated tricks like leaning back while lifting. A decoupled design gives the upper body to a manipulation policy (often the VLA's targets) and the lower body to a locomotion policy, joined by a shared balance term, which is easier to train and debug but leaves some coordination on the table.
🧠 Quiz
Imitation meets RL
Demonstrations and hand-written controllers get a robot most of the way; reinforcement learning is how it gets the last stretch: the contact-rich, millimetre-precise, never-quite-the-same part. This chapter is about combining the two, so RL starts from something that already works instead of from noise.
17Residual RL
Keep a base controller and learn only a correction on top of it:
The base can be a scripted trajectory, an inverse-kinematics or impedance controller, or a behaviour-cloned policy. RL only has to learn the part the base gets wrong (Silver et al., 2018; Johannink et al., 2019). Three things make that much easier than learning from scratch:
With \(a^\text{res}=0\) the robot already does something sensible, so even early rollouts reach the interesting states: here, the peg touching the hole.
Bounding the residual, \(\lVert a^\text{res}\rVert\le\delta\), bounds how far the learner can drag the robot from a behaviour you trust.
The residual only needs the inputs that explain the base's mistakes, often a handful, so a tiny network and a few minutes of search can be enough.
The task below. A Franka arm holds a 24 mm peg over a hole with 1.5 mm of clearance. The base is a Cartesian impedance controller, a virtual spring–damper on the peg tip, with the posture handled in the null space:
Its script is simple: move above where perception says the hole is, then descend. But perception is off by a few millimetres, as it always is. A flat-bottomed peg landing beside a hole feels only a vertical push, so a position controller has no idea which way to go and stalls on the surface.
The peg is not completely blind, though. When it rests half over the hole, the table pushes up only on the side that is still on the surface, so the wrist feels a torque. Dividing by the normal force gives the lever arm of that push, the centre of pressure, which points away from the hole:
The residual is a 5 → 8 → 2 tanh network with no bias terms, 56 parameters in all. No biases means zero input gives exactly zero output, so until the peg touches something the residual stays out of the way. Every 20 ms it reads the centre of pressure, the normal force and its own current offset, and outputs a sideways velocity for the target, capped at 3 cm/s and 14 mm in total. It was trained with the cross-entropy method, a derivative-free policy search, on random perception errors up to 9 mm: 64 candidate networks per iteration, 16 attempts each, 40 iterations, about 12 minutes on a 24-core desktop CPU. On 100 perception errors it never trained on, the scripted controller alone inserts the peg 6 times, a hand-tuned linear "follow the torque" law 75 times, and the learned residual 82 times.
Two things to notice. First, the network rediscovered a classic, roughly "move away from the centre of pressure", a learned cousin of the spiral and tilt searches assembly engineers hand-tune. It beats the hand-written linear version of the same idea mostly by easing off once the peg starts to drop in, instead of overshooting the hole. It still misses some attempts, usually the largest errors, where the peg barely overlaps the hole and the torque signal is faint. Second, the residual never sees a camera or the true hole position; it only fixes what the base controller can't. That division of labour is the whole point.
18Offline-to-online RL
Pretrain on a fixed dataset (logs, teleoperation, earlier experiments), then keep improving with live interaction. The offline half has one central problem: a Q-function trained by Bellman backups is queried at \(\max_{a'}Q(s',a')\), and the max happily picks actions that never appear in the data, where the network's value is pure extrapolation. Online, a wrong optimistic guess gets tried and corrected. Offline, nothing ever corrects it, and the error propagates through every backup.
Push Q down on whatever actions the current Q likes, up on the actions in the data: \(\min_Q\ \alpha\big(\mathbb E_s\log\sum_a e^{Q(s,a)}-\mathbb E_{(s,a)\sim\mathcal D}Q(s,a)\big)+\tfrac12\,\mathbb E\big[(Q-\mathcal B Q)^2\big]\)
Never query Q off the data. Fit \(V\) as an upper expectile of \(Q\) over dataset actions, \(L^\tau_2(u)=|\tau-\mathbb 1(u<0)|\,u^2\), and extract the policy by advantage-weighted regression: \(\max_\pi\mathbb E_{\mathcal D}\big[e^{\beta(Q-V)}\log\pi(a\mid s)\big]\).
Switching to online brings a second problem. A conservative Q underestimates, so the first online samples look surprisingly good, the critic recalibrates, and performance dips before it climbs. Cal-QL fixes that by never letting the conservative Q fall below a reference value, such as the Monte Carlo return of the behaviour policy. RLPD takes the opposite approach and skips offline pretraining entirely: plain SAC that samples each batch 50/50 from the offline and online buffers, with LayerNorm in the critics, a critic ensemble, and many gradient steps per environment step. It is simple, and it is what most real-robot systems now build on.
19RL fine-tuning of diffusion policies and VLAs
Large robot policies are pretrained by imitation, so they inherit everything about their demonstrations: the operator's hesitations, the failed grasps that were never cut out, the compounding errors of behaviour cloning. Fine-tuning them with RL is how they get past demonstrator level. Two routes, depending on what the policy is.
DPPO (Diffusion Policy Policy Optimisation, Ren et al., 2024) treats the denoising chain as part of the MDP. A diffusion policy samples \(a^K\sim\mathcal N(0,I)\) and refines it K times; each step is a Gaussian with a learned mean, so each has a log-likelihood, and PPO can push all of them at once:
For big VLAs, running PPO on billions of parameters is impractical, so the newer recipe keeps the training loss supervised and lets a learned value function decide what to learn from. Physical Intelligence's π*0.6 with RECAP trains a value function on autonomous rollouts and human corrections, labels every action with whether its advantage was positive, and conditions the policy on that label. At deployment it asks for "positive", with a guidance weight, much like classifier-free guidance in image models:
20Real-world RL
On hardware, every sample costs seconds of robot time, and every reset costs a person walking over. So real-world RL is an exercise in squeezing the most learning out of the fewest interactions. SERL and HIL-SERL (Luo et al., 2024) put the pieces together: an RLPD-style off-policy learner, a handful of demonstrations sampled 50/50 with online data, a learned reward classifier on camera images so nobody has to label success by hand, and human interventions: when the robot is about to do something useless or unsafe, an operator takes over with a spacemouse, and those corrective transitions go into both buffers. With all of that, precise tasks like inserting connectors or assembling parts reach near-perfect success in one to two hours of real interaction.
Several gradient steps per robot step. Compute is cheap and robot time is not; LayerNorm and critic ensembles keep high ratios stable.
\(r=\mathbb 1\big[c_\phi(o)>0.5\big]\), trained on a few hundred labelled success and failure images.
Riedmiller's framing: separate data collection from learning and keep every transition, so any later learner, on any objective, can reuse it.
🧠 Quiz
Deployment: safe, and on time
A policy that works in simulation has two more exams to pass. It must never do the one thing that breaks the robot or hurts someone, even while it is still learning. And it must produce the right action at the right moment, every cycle, on a small computer bolted inside the robot.
21Safety and constraints
Shaping a penalty into the reward ("−10 for hitting the table") only says that collisions are expensive, and a strong enough incentive will buy one anyway. A constrained MDP separates what you want from what you must not exceed:
The standard solver is the Lagrangian: turn the constraint into a penalty whose weight is learned, and climb in θ while descending in λ. The multiplier rises while the constraint is violated and decays to zero once it is comfortably satisfied, so you set the limit d, not the penalty:
Constraints that hold only on average are not enough for hardware, so a deployed system layers several mechanisms, from soft to hard:
Action and torque limits, joint-limit and self-collision penalties, action-rate and energy terms, constrained RL for the expected costs.
A safety filter: a control barrier function \(h(x)\ge0\) defines the safe set, and a tiny QP edits each action as little as possible to keep \(\dot h+\alpha h\ge0\).
Watchdogs that cut torque when the loop stalls, a hardware e-stop, and health monitoring: motor temperatures, tracking error, contact forces, logged and alarmed across the fleet.
22Deploying policies on edge hardware
A locomotion or whole-body policy is a small MLP: a few hundred thousand parameters, tens of microseconds on an embedded CPU or GPU. The network is almost never the bottleneck. The pipeline is: reading sensors over the fieldbus, state estimation, preprocessing, writing targets, and above all the occasional slow iteration. A control loop is judged by its worst case, not its average:
Hence the deployment rules of thumb. Run the loop at a fixed rate on an isolated core with real-time priority. Keep anything slow, such as the VLA or perception, asynchronous, publishing targets that the loop reads without waiting. Check observation parity: normalisation statistics, units, joint ordering, default poses and action scaling must match training exactly. Log real observations and replay them through the simulator policy to compare outputs. Quantise where it pays: the VLA, whose billions of weights make it memory-bandwidth bound, goes to INT8, FP8 or 4-bit weights. The whole-body controller is tiny, gains nothing measurable from quantisation, and feeds its errors straight into a feedback loop, so it stays in FP16 or FP32.
✦The whole stack, in one table
| Problem on a real robot | Tool | Topic |
|---|---|---|
| Sim and robot disagree | System ID, domain randomisation, actuator models, history-based adaptation | 5, 11 |
| Copying a demonstrator drifts | DAgger, noise injection, RL on the policy's own states | 6 |
| Data is free (simulation) | PPO with GAE, thousands of parallel environments, curricula | 7, 10, 13 |
| Data is expensive (hardware) | SAC / MPO / RLPD, demos, interventions, high update-to-data ratio | 8, 18, 20 |
| Sparse or unnatural behaviour | Potential-based shaping, motion imitation (DeepMimic, AMP, trackers) | 4, 14 |
| The robot sees less than the simulator | Asymmetric actor-critic, teacher–student distillation | 11 |
| Reasoning is slow, balance is fast | VLA on top, RL whole-body controller underneath, PD targets at 1 kHz | 12, 15 |
| A good controller is almost good enough | Residual RL; RL fine-tuning of diffusion policies and VLAs | 17, 19 |
| Learned policies can't be fully trusted | Constrained RL, safety filters, watchdogs and e-stops | 21 |
| It has to run, every cycle, on the robot | Asynchronous slow models, fixed-rate loops, parity checks, quantise the big model only | 22 |
🧠 Quiz
Cheat sheet & flashcards
Click a card to flip it. Try to recall the equation before you look.
🗺️ How it all fits together
| Method | Learns | Target | On/off-policy | Chapter |
|---|---|---|---|---|
| Policy / value iteration | v_π, v* | expected one-step backup (model) | — | 4 |
| MC prediction / ES control | V, Q | G_t | on | 5 |
| Off-policy MC | Q | ρ · G_t | off | 5 |
| TD(0) | V | R + γV(S′) | on | 6 |
| Sarsa | Q | R + γQ(S′,A′) | on | 6 |
| Q-learning | Q → q* | R + γ max Q(S′,·) | off | 6 |
| Expected Sarsa | Q | R + γ Σπ Q(S′,·) | either | 6 |
| Gradient MC / semi-grad TD | v̂(s,w) | G_t / R + γv̂(S′,w) | on | 9 |
| Semi-gradient Sarsa | q̂(s,a,w) | R + γq̂(S′,A′,w) | on | 10 |
| REINFORCE (+baseline) | π(a|s,θ) | G_t (− b(s)) | on | 13 |
| Actor–critic | π(a|s,θ) + v̂(s,w) | δ = R + γv̂(S′) − v̂(S) | on | 13 (draft 11) |