Adithya Balaji

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.

🎰 bandit duel❌⭕ self-learning tic-tac-toe🧮 Bellman equation explorer 🗺️ paint-your-own DP gridworld🃏 Monte Carlo blackjack🧗 cliff walking race 🚗 mountain car🎯 policy gradient on a tricky corridor
🔩 Franka peg-in-hole, live in MuJoCo✂️ PPO clip vs no clip🤖 sim-to-real deploy🏎️ DAgger🧍 a slow brain on a fast spine🗄️ offline Q off the data🛡️ safety filter⏲️ control-loop budget
Chapter 1 (+ Ch. 2 bandits)

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

🤖 Agent 🌍 Environment action Aₜ state Sₜ₊₁ reward Rₜ₊₁

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

🧭Policyπ(a|s)
A mapping from states to actions (or action probabilities). It is the agent's behaviour, and could be a lookup table, a rule, or a neural net.
🍬Reward signalRₜ
Defines the goal. It is immediate and intrinsic: what is good right now. The agent can't change how rewards are computed.
💎Value functionv(s), q(s,a)
What is good in the long run: the expected total future reward from a state. Actions are chosen based on values, but values must be estimated from experience.
🔮Modelp(s′, r | s, a)
Optional. It predicts how the environment responds, which enables planning. Methods without one are model-free trial-and-error learners.

🎰 Bandit duel: you vs. the bot Ch. 2 · exploration vs exploitation

There are 10 slot machines, each with a hidden mean payout q*(a) ~ N(0,1) and noisy rewards. You and the bot each get 50 pulls. Click a machine to pull it; the bot pulls at the same time (pink dot). Can you balance exploring and exploiting better than an algorithm?

your total
0
pulls
0
bot total
0
best arm
???

🧪 The 10-armed testbed Fig. 2.2 / 2.3 / 2.4

Average 1000 steps over many random bandit problems. Greedy gets stuck, ε-greedy keeps improving, optimistic initial values explore early on purpose, and UCB explores where it is most uncertain.

$$Q_{n+1} = Q_n + \frac{1}{n}\big[R_n - Q_n\big] \qquad A_t = \arg\max_a \Big[Q_t(a) + c\sqrt{\tfrac{\ln t}{N_t(a)}}\Big]$$

General pattern used throughout the book: NewEstimate ← OldEstimate + StepSize · [Target − OldEstimate]

❌⭕ Tic-tac-toe that learns from experience Sec. 1.5

The book's opening example. The bot (✕) keeps a table V(s) holding its estimated probability of winning from each board. After every greedy move it nudges the previous board's value toward the new one: \(V(S_t) \leftarrow V(S_t) + \alpha\,[V(S_{t+1}) - V(S_t)]\), which is a temporal-difference update. Train it, then play against it. The % numbers show its value estimate for each move it is considering.

games trained
0
states in table
0

🧠 Quiz

Chapter 3

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.

Return

\(G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots = R_{t+1} + \gamma G_{t+1}\)

State value

\(v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s]\)

Action value

\(q_\pi(s,a) = \mathbb{E}_\pi[G_t \mid S_t = s, A_t = a]\)

🧮 Discounting playground Sec. 3.3

Click rewards to change them. Each chip shows its \(G_t\), computed backwards with \(G_t = R_{t+1} + \gamma G_{t+1}\). Low γ makes the agent short-sighted; γ → 1 makes it far-sighted.

G₀
effective horizon 1/(1−γ)

The Bellman equations

$$v_\pi(s) = \sum_a \pi(a\mid s) \sum_{s',r} p(s',r\mid s,a)\,\big[r + \gamma\, v_\pi(s')\big]$$ $$v_*(s) = \max_a \sum_{s',r} p(s',r\mid s,a)\,\big[r + \gamma\, v_*(s')\big] \qquad q_*(s,a) = \sum_{s',r} p(s',r\mid s,a)\big[r + \gamma \max_{a'} q_*(s',a')\big]$$

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.

🔍 Bellman equation explorer Example 3.5 gridworld

Every move from A teleports you to A′ with reward +10, and every move from B teleports you to B′ with reward +5. Bumping into the edge gives −1. Click any cell to see its Bellman equation with real numbers. The dashed cyan cells are its successors.

Try this: set A's reward to 4 or less in v_* mode and watch the optimal policy switch to going for B instead. Then lower γ and see the agent become myopic.

🤖 Recycling robot Example 3.3

With a high battery, the robot can search for cans (r_search) or wait (r_wait). Searching drains the battery to low with probability 1−α. With a low battery, searching keeps it low with probability β; otherwise the battery dies and the robot is rescued (−3). It can also recharge. The bars show \(q_*\) for each action, and the best one is highlighted.

🧠 Quiz

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.

Iterative policy evaluation

\(v_{k+1}(s) = \sum_a \pi(a|s) \sum_{s',r} p(s',r|s,a)[r + \gamma v_k(s')]\)

Policy improvement

\(\pi'(s) = \arg\max_a \sum_{s',r} p(s',r|s,a)[r + \gamma v_\pi(s')]\)

Value iteration

\(v_{k+1}(s) = \max_a \sum_{s',r} p(s',r|s,a)[r + \gamma v_k(s')]\)

🗺️ DP gridworld playground paint walls · goals · fire pits

Pick a preset or paint your own world, then step through the algorithms. Sutton 4×4 reproduces Example 4.1: press "Eval 1 sweep" repeatedly to watch Figure 4.1 unfold. Arrows show the policy π; arrow length is proportional to probability.

paint:
sweeps
0
last Δ
—
Experiments to try: (1) In the maze, raise the slip probability and watch the policy move away from the fire pits. (2) Make the step reward positive with γ = 1 and see what goes wrong (no incentive to finish!). (3) Compare how many sweeps policy iteration and value iteration need.

🎲 Gambler's problem Example 4.3

A gambler bets on coin flips (heads with probability p_h) and wants to reach $100. Value iteration finds the probability of winning from each amount of capital, and the optimal stakes have a strange fractal-like shape. Drag p_h: above 0.5, the optimal play is to make timid bets of $1.

🧠 Quiz

Chapter 5

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.

MC prediction

\(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)]\)

Importance-sampling ratio

\(\rho_{t:T-1} = \prod_{k=t}^{T-1} \frac{\pi(A_k|S_k)}{b(A_k|S_k)}\)

Ordinary vs weighted IS

\(V(s) = \frac{\sum \rho\, G}{|\mathcal{T}(s)|}\)  vs  \(V(s) = \frac{\sum \rho\, G}{\sum \rho}\)

🃏 Monte Carlo Blackjack Examples 5.1, 5.3, 5.4

States are (player sum 12–21, dealer's showing card, usable ace?). The deck is infinite, the dealer sticks on 17+, and the reward is +1 / 0 / −1.

Evaluate the policy "stick only on 20 or 21" (Fig. 5.1). After 10k episodes the surface is noisy; after 500k it is smooth. Notice the cliff at sums 20–21, and how a dealer ace hurts you.

episodes: 0

Monte Carlo with Exploring Starts (Fig. 5.2). Every episode starts from a random state and action, then follows the current greedy policy. Purple H = hit, teal S = stick. Run 1M+ episodes to approach the book's figure.

episodes: 0
Dealer —
You —

The advisor uses the q-table learned in the MC control tab. Train it with a few million episodes and it plays close to optimal "basic strategy". Its advice comes from nothing but averaged experience, with no knowledge of the rules.

Example 5.4: estimate the value of a single state (sum 13 with a usable ace, dealer shows 2) under the target policy "stick on 20/21", using episodes from a random behaviour policy. Ordinary IS is unbiased but has huge variance; weighted IS is biased early on but far more stable.

🧠 Quiz

Chapter 6

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.

TD(0)

\(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]\)

Sarsa (on-policy)

\(Q(S,A) \leftarrow Q(S,A) + \alpha[R + \gamma Q(S',A') - Q(S,A)]\)

Q-learning (off-policy)

\(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

DP: full expected backup, one step deep (needs a model)
MC: one sampled trajectory, all the way to the end
TD(0): one sampled step, then bootstrap from V(S′) V(S′) estimate
needs model?bootstraps?samples?online / incomplete episodes?
Dynamic Programmingyesyesno— (sweeps)
Monte Carlononoyesno
Temporal-Differencenoyesyesyes

🚶 Random walk: TD vs MC Example 6.2

Start at C and step left or right with equal probability. Reaching the right end gives +1; everything else gives 0. True values are 1/6 … 5/6. Watch one episode animate: TD updates every step using the next state's estimate, while MC waits until the episode ends.

Press play to watch an episode.

🧗 Cliff walking race: Sarsa vs Q-learning vs Expected Sarsa Example 6.6 & 6.5

Each agent learns in its own copy of the world. The coloured line is the current greedy path and the white dot is the agent. On the cliff, Q-learning learns the optimal path along the edge, but its ε-exploration keeps throwing it off, so Sarsa earns more reward online by taking the safe route. Switch to the Windy gridworld for a different challenge. Set speed to 1 to watch individual steps.

$$\text{Expected Sarsa:}\quad Q(S,A) \leftarrow Q(S,A) + \alpha\Big[R + \gamma \sum_a \pi(a\mid S')\,Q(S',a) - Q(S,A)\Big]$$

🧠 Quiz

Chapters 9–10 (final ed.) · Ch. 9 in your draft

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.

Objective

\(\overline{VE}(\mathbf w) = \sum_s \mu(s)\,[v_\pi(s) - \hat v(s,\mathbf w)]^2\)

(Semi-)gradient update

\(\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)

Linear

\(\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)\)

📈 1000-state random walk Examples 9.1–9.2, Fig. 9.1–9.5

There are 1000 states. From each one you jump uniformly 1–100 states left or right; leaving the left edge gives −1 and the right edge gives +1. Pick a feature construction and watch \(\hat v\) (cyan) approach the true value (dashed yellow). The lower-left plot shows what the individual features look like.

episodes
0
√VE
—
# weights
—
Try: aggregation with 10 groups gives a staircase (Fig. 9.1). Semi-gradient TD with aggregation is visibly biased near the edges compared with MC. A polynomial of order 20 is unstable unless α is tiny, while Fourier order 20 copes. Tile coding with 1 tiling vs 50 tilings shows the gain in resolution from overlapping offsets.

🚗 Mountain Car: semi-gradient Sarsa + tile coding Example 10.1 (final) / Sec. 9.4 (draft)

The car's engine is too weak to drive straight up the hill, so it must rock back and forth to build momentum. The agent gets −1 per step, uses 8 tilings of 8×8 tiles over (position, velocity), and starts with optimistic q = 0, so it explores even with ε = 0. The right-hand heatmap is the learned cost-to-go \(-\max_a \hat q(s,a,\mathbf w)\) (Fig. 10.1); the white trace is the current trajectory in phase space.

episodes
0
last length
—
$$\mathbf w \leftarrow \mathbf w + \alpha\big[R_{t+1} + \gamma\,\hat q(S_{t+1},A_{t+1},\mathbf w) - \hat q(S_t,A_t,\mathbf w)\big]\nabla \hat q(S_t,A_t,\mathbf w)$$

🧠 Quiz

Chapter 13 (final ed.) · Ch. 11 in your draft

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.

Policy gradient theorem

\(\nabla J(\boldsymbol\theta) \propto \sum_s \mu(s) \sum_a q_\pi(s,a)\,\nabla \pi(a\mid s,\boldsymbol\theta)\)

REINFORCE (with baseline)

\(\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)\)

One-step actor–critic

\(\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)\)

🍕 Softmax policy & the ∇ln π trick Eq. 13.2, 13.9

\(\pi(a) = e^{h(a)/\tau} / \sum_b e^{h(b)/\tau}\). Give a 👍 (R = +1) or 👎 (R = −1) to an action and watch the REINFORCE update \(\theta \mathrel{+}= \alpha R\,\nabla\ln\pi(a)\). For a softmax policy, \(\nabla \ln\pi(a) = \mathbf{1}_a - \pi\), so the chosen action goes up and all the others go down.

preferences h = []

Try lowering τ: the policy becomes nearly deterministic, like a greedy one.

🎯 Short corridor with switched actions Example 13.1, Fig. 13.1–13.2

There are three non-terminal states and every step costs −1. In the second state the actions are reversed. The agent's features can't tell the states apart, so all it can choose is a single probability p of going right. Any ε-greedy policy is stuck at the red dots, but the best stochastic policy (p ≈ 0.59) does far better. Train a policy-gradient agent and watch it climb J(θ).

J(slider p)
—
agent p(right)
—
episodes
0
Compare: REINFORCE with α = 2⁻¹³ is slow and noisy. Adding a baseline lets you use a much bigger step (2⁻⁹) and converge faster (Fig. 13.2). Actor–critic bootstraps with a learned critic and updates online, during the episode.

🧠 Quiz

Advanced · A

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:

$$V^\pi(s)=\mathbb E_\pi\big[G_t\mid S_t=s\big],\qquad Q^\pi(s,a)=\mathbb E_\pi\big[G_t\mid S_t=s,\,A_t=a\big],\qquad G_t=\sum_{k\ge0}\gamma^k R_{t+k+1}$$

They are tied together by two one-line identities. Chain them and you get the Bellman equations from Chapter 3:

Q from V (one step of the world)

\(Q^\pi(s,a)=\mathbb E\big[R+\gamma V^\pi(S')\mid s,a\big]\)

V from Q (one step of the policy)

\(V^\pi(s)=\sum_a\pi(a\mid s)\,Q^\pi(s,a)\)

Optimality

\(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".

📊 Advantage meter A = Q − V

A gripper hovers over a cup and has five options. Drag the bars to set each Q-value. The policy is a softmax over Q with temperature τ; the dashed line is \(V=\sum_a\pi(a)Q(a)\). Bars above the line have positive advantage, and the policy gradient raises their probability. Notice that the π-weighted advantages always cancel.

V = Σ π·Q
—
max Q (greedy value)
—
Σ π·A
—
Press "+1 to every Q": V moves, every Q moves, but the advantages and the policy don't change. That is why subtracting a baseline is free: it changes the variance of the gradient, not its direction on average.

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:

$$\mathbb E_{a\sim\pi_\text{new}}\big[f(a)\big]=\mathbb E_{a\sim\pi_\text{old}}\Big[\underbrace{\tfrac{\pi_\text{new}(a)}{\pi_\text{old}(a)}}_{r(a)}\,f(a)\Big],\qquad \text{ESS}=\frac{\big(\sum_i r_i\big)^2}{\sum_i r_i^2}$$

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.

On-policy (PPO, TRPO, A2C)

Stable and simple, but sample-hungry. Fine when a GPU simulator hands you millions of steps an hour.

Off-policy (SAC, MPO, TD3, DQN)

Reuses every transition, so far more sample-efficient, but bootstrapping on stale data is less stable. The usual choice on real hardware.

⚖️ When does old data stop being useful? importance ratio · ESS · PPO clip

The grey curve is the old policy, a Gaussian over a 1-D action, and the ticks are 300 actions it took. Move the new policy away and watch the weights (tick heights) explode and the effective sample size fall. The shaded band is where PPO would trust the ratio, \(1-\epsilon\le r\le1+\epsilon\).

ESS / N
—
true E_new[reward]
—
IS estimate
—
samples inside clip
—
The reward here is a bump at a = 1.5 (thin line). Push μ past 2 with σ = 0.4: the estimate starts to jump every time you resample, because it rests on two or three samples. That variance, not bias, is what kills naive off-policy policy gradients.

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:

Action noise

\(a=\mu_\theta(s)+\sigma\,\xi\), with \(\xi\sim\mathcal N(0,I)\). The continuous cousin of ε-greedy.

Maximum entropy

\(J=\mathbb E\big[\sum_t r_t+\alpha\,\mathcal H(\pi(\cdot\mid s_t))\big]\). Exploration becomes part of the objective (SAC).

Intrinsic reward

\(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.

$$x_{t+1}=x_t+\theta(0-x_t)\,\Delta t+\sigma\sqrt{\Delta t}\,\xi_t \qquad\qquad a_t=\beta\,a_{t-1}+(1-\beta)\,\tilde a_t$$

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.

🦾 Three ways to wiggle an arm white · OU · smoothed

A gripper tip is driven by velocity commands that are pure exploration noise. All three draw the same white noise each step. OU keeps the command's spread at σ with correlation \(\rho=1-\theta\Delta t\); smoothing shrinks it. Watch how much of the workspace each one visits, and how violently the commands change (the action rate, which the motors feel).

Higher correlation means the commands keep their direction for longer, so the tip travels further per unit of noise. Too much and it explores one direction for ages. This is also why many robot policies penalise the action rate \(\lVert a_t-a_{t-1}\rVert^2\) in the reward.

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

$$F(s,s')=\gamma\,\Phi(s')-\Phi(s)\qquad\Rightarrow\qquad\sum_{t=0}^{T-1}\gamma^tF(s_t,s_{t+1})=\gamma^T\Phi(s_T)-\Phi(s_0)$$

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.

🍪 Three rewards, one gridworld sparse · bonus · potential-based

Three Q-learning agents train side by side on the same 9×9 room with a wall. Sparse gets +1 at the goal. "Closeness bonus" also gets \(b\cdot(1-d/d_{\max})\) every step. "Potential" gets \(\gamma\Phi(s')-\Phi(s)\) with \(\Phi(s)=\gamma^{d(s)}\). Here \(d\) is the walking distance around the wall. Episodes time out after 150 steps. The small maps show each agent's greedy path after training.

With b = 0.1 and γ = 0.95, camping on the cell next to the goal earns about 0.094 every step, worth 0.094 / (1 − 0.95) ≈ 1.9 in total, more than the +1 for arriving. Watch the bonus agent learn to camp. Set b to 0.02, or γ to 0.8, and it behaves again. Potential-based shaping never needs that tuning, and it learns in a couple of dozen episodes where sparse needs a hundred.

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:

System identification

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.

Domain randomisation

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:

🤖 Train in sim, deploy to "real" domain randomisation · system ID

The policy is a PD controller \(u=K_p(q^*-q)-K_d\dot q\) that moves a joint to a target, and training means picking the gains with the lowest average cost over the training distribution. The map shows how well the trained gains do on every possible robot (mass × sensing delay). The box is what training saw; the hidden real robot is somewhere on the map.

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

$$J(\hat\pi)\;\le\;J(\pi^*)+T^2\epsilon\quad\text{(BC)}\qquad\qquad J(\hat\pi)\;\le\;J(\pi^*)+O(T\epsilon)\quad\text{(DAgger)}$$
DAgger

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).

Noise injection

Perturb the expert while recording (DART), so the data already contains recoveries from small mistakes.

RL

Optimises on its own state distribution with a reward, so recovery is learned. And unlike BC, it can exceed the demonstrator.

🏎️ Clone a driver, then DAgger it compounding error · data coverage

The expert steers back to the centre line. The learner is a lookup table over (lateral offset, heading error): it copies the expert's average correction in every cell it has data for, and does nothing extra in empty cells. Every rollout has a little steering noise. On the right, blue cells have expert labels (darker = more) and dots are where the clone actually drove.

labelled states
0
laps finished (of 10)
—
avg distance before crash
—
DAgger iterations
0
The clean demos only cover the middle cell or two, so the moment the clone drifts it has no idea how to come back. Two or three DAgger iterations fill in exactly the cells it actually visits. Noise injection gets part of the way there before the learner ever drives.

🧠 Quiz

Advanced · B

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:

$$L^{\text{CPI}}(\theta)=\hat{\mathbb E}_t\big[r_t(\theta)\,\hat A_t\big],\qquad r_t(\theta)=\frac{\pi_\theta(a_t\mid s_t)}{\pi_{\theta_\text{old}}(a_t\mid s_t)}$$

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:

$$L^{\text{CLIP}}(\theta)=\hat{\mathbb E}_t\Big[\min\big(r_t\hat A_t,\;\operatorname{clip}(r_t,1-\epsilon,1+\epsilon)\,\hat A_t\big)\Big]$$

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\):

$$\delta_t=r_t+\gamma V(s_{t+1})-V(s_t),\qquad \hat A^{\text{GAE}(\gamma,\lambda)}_t=\sum_{l=0}^{\infty}(\gamma\lambda)^l\,\delta_{t+l}$$

\(\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\).

Normalise advantages

Per minibatch, \(\hat A\leftarrow(\hat A-\mu)/\sigma\). Keeps the step size meaningful as rewards change scale.

Adaptive learning rate

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.

Why it dominates

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.

✂️ Clipped vs unclipped, same data budget PPO surrogate · KL

Two agents learn a 1-D Gaussian policy to hit a narrow reward bump at a = 2 from noisy rewards. Each iteration collects 32 actions, then runs K epochs of gradient ascent on its surrogate. One uses the clip; the other optimises \(r\hat A\) unclipped. Both have the same entropy bonus. Run a few iterations and watch the KL per update and where each policy ends up.

Unclipped, K epochs on 32 noisy samples is K chances to overfit them: σ collapses onto whichever sample got lucky, and the KL per update is often hundreds of times larger. With the clip, every sample whose ratio has left \([1-\epsilon,1+\epsilon]\) in its favour stops contributing, so the update stops by itself. With K = 1 the ratio is exactly 1 on the only epoch, so the clip never fires and the two agents run the same algorithm.

🎚️ Picking λ GAE bias–variance

A robot walks 60 steps down a corridor; each step pays \(0.1+\sigma\xi\). Its critic is lazy, \(V_\phi=(1-e)\,V\), as critics early in training are. Here the bias and variance of the GAE estimate have closed forms. The left plot shows them against λ; the right shows the weights \((\gamma\lambda)^l\) that GAE puts on each future TD error.

best λ (min MSE)
—
effective horizon 1/(1−γλ)
—
MSE at chosen λ
—
Set the critic error to 0 and the best λ drops to 0: a perfect critic makes bootstrapping free. Turn the reward noise down and it climbs towards 1. Real training has both a rough critic and noisy returns, and 0.9 to 0.97 is where the curve bottoms out.

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:

$$J(\pi)=\sum_t\mathbb E\Big[r(s_t,a_t)+\alpha\,\mathcal H\big(\pi(\cdot\mid s_t)\big)\Big],\qquad \mathcal H(\pi)=-\mathbb E_{a\sim\pi}\big[\log\pi(a)\big]$$

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:

$$Q(s,a)=r+\gamma\,\mathbb E_{s'}\big[V(s')\big],\qquad V(s)=\mathbb E_{a\sim\pi}\big[Q(s,a)-\alpha\log\pi(a\mid s)\big],\qquad \pi^*(a\mid s)\propto\exp\!\big(Q(s,a)/\alpha\big)$$
Twin critics

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.

Automatic α

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.

Reparameterisation

\(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.

$$\textbf{E-step: }\ q(a\mid s)\propto\pi_\text{old}(a\mid s)\,\exp\!\big(Q(s,a)/\eta\big),\quad \operatorname{KL}(q\,\|\,\pi_\text{old})\le\epsilon$$
$$\textbf{M-step: }\ \max_\theta\ \mathbb E_{q}\big[\log\pi_\theta(a\mid s)\big],\quad \operatorname{KL}(\pi_\text{old}\,\|\,\pi_\theta)\le\epsilon_m$$

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.

🌡️ Temperature and the soft-optimal policy π ∝ exp(Q/α) · auto-α

One state, a 1-D action, and a Q-function with a sharp tall peak and a broad lower one. The soft-optimal policy is \(\pi(a)\propto e^{Q(a)/\alpha}\). Slide α, or set a target entropy and let SAC's α update, \(\log\alpha\leftarrow\log\alpha-\beta\,(\mathcal H-\bar{\mathcal H})\), find the temperature for you.

α
—
entropy H(π)
—
E_π[Q]
—
mass on the sharp peak
—
At high α the policy hedges between both hills; at low α it commits to the sharp one. This is a continuous-action entropy, so it can go negative once the policy is narrower than a unit-wide uniform. That is why target entropies like \(-\dim\mathcal A\) are negative numbers.

🪜 MPO, one trust-region step at a time E-step · M-step · η from the dual

Same Q-function. The grey Gaussian is the current policy. The E-step reweights it by \(e^{Q/\eta}\) (shaded), with η solved by bisection so that \(\operatorname{KL}(q\|\pi_\text{old})=\epsilon\) exactly. The M-step fits a new Gaussian to that shape (blue). Step a few times.

η (solved)
—
policy μ, σ
—
E_π[Q]
—
steps
0
From the middle with ε = 0.1, MPO climbs the nearest broad hill and never finds the taller, sharper one at a = 1.6: every step is a small, safe move. Start the mean at 1 and it does. Now try ε = 1 from the middle: q becomes two-humped, and a Gaussian fitted to it can only straddle both, sitting in the valley. That is one reason MPO bounds the M-step too, and why richer policy classes help.

🎲 Why two critics overestimation · clipped double Q

Every action has true value 0. A critic's estimates are 0 plus noise. The Bellman target uses the max, \(\max_a\hat Q(s',a)\), which is positive on average even though every true value is 0. Twin critics take the second critic's estimate at the first critic's chosen action and keep the smaller, \(\min(\hat Q_1,\hat Q_2)\).

E[max Q̂] (single)
—
E[min(Q̂₁,Q̂₂)] (twin)
—
single, compounded over γ=0.99
—
The bias feeds itself: each target is built from estimates that were already inflated, so in the worst case it adds up as \(\sum_k\gamma^k\,b=b/(1-\gamma)\), a hundred times the per-step bias at γ = 0.99. Clipped double Q is slightly pessimistic instead, and pessimism is much safer: the policy doesn't chase actions that only look good.

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^*_{t:t+H}=\arg\max_{a_{t:t+H}}\ \sum_{k=0}^{H-1}\gamma^k\,\hat r(\hat s_k,a_k)+\gamma^H\,\hat V(\hat s_H),\qquad \hat s_{k+1}=\hat f_\psi(\hat s_k,a_k),\ \hat s_0=s_t$$
DreamerV3

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.

TD-MPC2

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.

🧭 A planner, a learned model, and a wall it hasn't met MPC · CEM · model exploitation

The robot's model was learned from random wandering near the start, so it believes the room is empty. The real room has a wall (dashed). Each real step, CEM optimises H moves in the model (the imagined plan is dotted) and executes the first. With "learn online" on, a move that stops dead teaches the model a wall cell (dark).

real steps
0
wall cells learned
0
status
ready
Turn learning off: the planner pushes into the wall forever, because in its model the straight line works. Turn it on with H = 6: it learns the wall but still dithers, since no 6-step plan around it looks better than waiting. A longer horizon, or a learned value at the end of a short one (the TD-MPC2 recipe), gets it around.

🧠 Quiz

Advanced · C

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.

Simulators

Isaac Lab (on Isaac Sim), MuJoCo MJX and MuJoCo Playground, Genesis, and Newton (NVIDIA, Google DeepMind and Disney Research).

Reference code

legged_gym + rsl_rl (ETH Zürich): the compact PPO most legged-robot work still starts from.

The batch

\(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

$$\text{throughput}_\text{GPU}(N)=\frac{N}{t_0+N/R_{\max}}\ \xrightarrow{\;N\to\infty\;}\ R_{\max},\qquad \text{throughput}_\text{CPU}(N)=\frac{N}{\lceil N/n_\text{cores}\rceil\,t_\text{env}}$$

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:

$$y_t=\begin{cases}r_t & \text{true terminal (fell over)}\\ r_t+\gamma\,V(s_{t+1}) & \text{time-out or rollout boundary}\end{cases}$$

🐜 How many robots at once? throughput · wall-clock

Slide the number of parallel environments. The fleet on the left is drawn one dot per robot (up to 4096). The plot uses illustrative numbers: a GPU with 4 ms of launch overhead per step and a ceiling of 400k env-steps per second, against a 32-core CPU at 1.2 ms per env-step. The target is a 150M-step locomotion run.

GPU env-steps / s
—
CPU env-steps / s
—
150M steps on GPU
—
… on CPU
—
Below a few hundred environments the GPU loses: you are paying launch overhead to simulate almost nothing. Past a few thousand it saturates and more environments only make the batch bigger. That cheap, huge batch is exactly the regime where on-policy PPO beats sample-efficient off-policy methods on wall-clock time.

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:

Asymmetric actor-critic

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.

Teacher–student

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.

🛷 Teacher, student and blind policy on changing ground privileged info · history window

A sled must hold speed 1 while the ground goes carpet → ice → mud → carpet. Holding speed needs the drag c as a feed-forward term. The teacher reads c from the simulator. The blind policy assumes c = 1. The student estimates c by least squares over its last k noisy speed readings, \(\hat c=\sum v\,(u-\Delta v/\Delta t)/\sum v^2\).

speed error, teacher
—
student
—
blind
—
Find the best window for the default noise: somewhere around 10 to 20 steps. Shorter and the estimate is a blur of sensor noise; longer and it is still averaging the carpet while the sled is on ice. Set the noise to 0 and the shortest window wins. A learned adaptation module faces the same trade-off and learns where to sit on it.

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:

$$q^\text{target}_t=q^\text{default}+s\cdot a_t,\qquad \tau=K_p\big(q^\text{target}-q\big)-K_d\,\dot q,\qquad |\tau|\le\tau_{\max}$$

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:

$$\omega_n=\sqrt{K_p/I},\qquad \zeta=\frac{K_d}{2\sqrt{K_p\,I}}$$
Gains and scale

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.

History and latency

Feed the last few observations and actions back in. It handles partial observability and lets the policy model its own delay.

Smoothness

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.

🦵 Tune a leg joint PD targets · rate · latency

An ideal policy sends position targets that follow a swing-leg trajectory (dashed). The targets are held between policy steps (purple staircase), arrive after the latency, and are tracked by a 1 kHz PD loop against gravity with a 12 N·m torque limit (ink).

ω_n / ζ
—
tracking RMSE (rad)
—
time at torque limit
—
target jumps Σ(Δq*)²
—
Things to try. Raise Kp to 160 with Kd 0.5: ζ falls below 0.1 and the joint buzzes at the torque limit. Keep Kp 80, Kd 1.5 and add 20 ms of latency: the error nearly doubles. Push the policy rate from 50 to 200 Hz: almost nothing changes, because the PD loop already handles the fast part. Smoothing lowers the target jumps, but costs tracking.

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

$$\operatorname{Var}[\text{success}]=p\,(1-p),\qquad \text{maximal at }p=\tfrac12,\ \text{zero at }p=0\text{ and }p=1$$

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.

🪜 Three ways to pick terrain p(1−p) · terrain game

256 environments share one policy with a scalar skill s. At level ℓ an episode succeeds with \(p=\sigma\big(2.2\,(s-\ell)\big)\), and each iteration the skill grows in proportion to the summed \(p(1-p)\). One run trains everyone on the hardest level 10, one samples levels uniformly, and one plays the terrain game (up on success, down on failure). The stairs show where the terrain-game robots currently are.

"Hardest only" never moves: p ≈ 0 everywhere means zero signal. Uniform learns, but most of its robots sit on levels that are far too easy or far too hard. The terrain game parks every robot on the frontier, and the whole staircase climbs with the skill.

🧠 Quiz

Advanced · D

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:

$$r_t=w_p\,e^{-k_p\sum_j\lVert\hat q_j-q_j\rVert^2}+w_v\,e^{-k_v\sum_j\lVert\hat{\dot q}_j-\dot q_j\rVert^2}+w_e\,e^{-k_e\sum_e\lVert\hat p_e-p_e\rVert^2}+w_c\,e^{-k_c\lVert\hat p_c-p_c\rVert^2}$$

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:

$$\min_D\ \mathbb E_{\mathcal M}\big[(D(s,s')-1)^2\big]+\mathbb E_{\pi}\big[(D(s,s')+1)^2\big],\qquad r^\text{style}=\max\!\big(0,\ 1-\tfrac14\,(D(s,s')-1)^2\big),\qquad r=w_g\,r^\text{task}+w_s\,r^\text{style}$$

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.

🕺 Be the policy DeepMimic tracking reward

The ghost walks a reference gait. The solid figure is you: drag its knees and feet to match the ghost at the paused phase, or let a PD tracker follow on its own. The reward is \(0.7\,r_p+0.3\,r_e\) (pose and feet; velocity left out while paused). Change the kernel scales and feel how sharp or forgiving the reward becomes.

pose term r_p
—
feet term r_e
—
reward r
—
Push kp to 20: the reward is near zero unless you are almost exactly right, which is a sparse reward in disguise. Drop it to 0.2 and sloppy poses score almost as well as perfect ones. The scales in DeepMimic (2 for pose, 40 for end-effectors in metres) are chosen so typical early errors still give a usable gradient.

🎭 A discriminator as a reward AMP · mode collapse

The dataset holds two styles of gait, walking and jogging, as points in (stride, cadence). The policy is a small Gaussian blob. Each round the discriminator (an RBF network trained with the LSGAN loss) learns to separate data from policy, and the policy takes a policy-gradient step on the style reward (shaded). Watch where it ends up.

It settles on one style and ignores the other: mode collapse, the classic GAN failure, and why AMP setups add latent skill codes or diversity terms when they need several styles. Restart far away and nothing happens at all: the discriminator wins outright, the style reward is zero everywhere the policy goes, and there is no gradient to follow.

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:

High level: the VLA

1–10 Hz, sometimes slower. Reads cameras and language; outputs targets: end-effector poses, base velocity, keypoints, often as a chunk of future targets.

Low level: an RL whole-body controller

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):

$$\ddot x=\omega^2\,(x-p),\qquad \omega=\sqrt{g/z}\approx3.3\ \text{s}^{-1}\ \text{for}\ z=0.9\ \text{m},\qquad \xi=x+\dot x/\omega\ \ \text{(capture point)}$$

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.

🧍 A slow brain on a fast spine LIPM · rates · latency

The VLA wants the body to lean to a few targets in turn (dashed). In direct mode it computes the balance action itself, at its own rate and latency. In hierarchical mode it only sends the target, and a 50 Hz capture-point controller does the balancing. The ZMP is limited to a 20 cm foot.

result
—
mean tracking error
—
Direct mode survives at 10 Hz with no latency and falls at 3 Hz, or at 10 Hz with 100 ms of latency. Switch to hierarchical and even 1 Hz with 300 ms of latency stays up: the targets arrive late, so tracking is sloppier, but balance never depends on the slow loop.

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:

$$x_c=\frac{M\,x_\text{body}+m\,x_\text{load}}{M+m},\qquad p=x_c-\frac{z_c}{g}\,\ddot x_c,\qquad |p|\le\ell_\text{foot}$$

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.

📦 Carry the box centre of mass · ZMP

A 60 kg humanoid holds a box in front of it. Change the box's mass and reach, and the walking acceleration. With the balance term on, the controller leans the body back by just enough to bring the combined centre of mass over the ankle, the behaviour a unified policy learns by itself.

centre of mass
—
ZMP
—
status
—
20 kg at 0.6 m tips the robot forward without the balance term. With it, the lean fixes standing still, but speeding up or braking hard (±1.5 m/s²) still pushes the ZMP out of the foot: to the heel when accelerating, to the toes when braking. That is why loco-manipulation policies watch the load and the walking command together, not one at a time.

🧠 Quiz

Advanced · E

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:

$$a_t=a^\text{base}(s_t)+a^\text{res}_\theta(s_t),\qquad \lVert a^\text{res}_\theta\rVert\le\delta,\qquad \max_\theta\ J\big(a^\text{base}+a^\text{res}_\theta\big)$$

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:

Exploration starts near success

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.

Safety by construction

Bounding the residual, \(\lVert a^\text{res}\rVert\le\delta\), bounds how far the learner can drag the robot from a behaviour you trust.

A small problem

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:

$$\tau=J^\top\big[K(x^*-x)-D\,\dot x\big]+\underbrace{c(q,\dot q)+g(q)}_{\text{gravity, Coriolis}}+\big(I-J^\top J^{+\top}\big)\,\tau_\text{posture}$$

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:

$$\boldsymbol\tau=\mathbf r_c\times\mathbf F\quad\Rightarrow\quad \mathbf r_c^{xy}\approx\frac{1}{F_z}\begin{pmatrix}-\tau_y\\ \tau_x\end{pmatrix}$$

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.

🔩 Franka peg-in-hole, with and without the residual MuJoCo in your browser

Real physics: MuJoCo running as WebAssembly, with the Franka Emika Panda model from MuJoCo Menagerie. Each attempt draws a new perception error. Untick the residual to watch the scripted controller alone. Drag to orbit, scroll to zoom.

about 3 MB, loaded only when you press the button
perception error
—
depth
—
—

Panda model: MuJoCo Menagerie, Apache-2.0, meshes simplified for the web. Physics: MuJoCo 3.16, Apache-2.0. Both are served from this site.

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.

CQL (conservative Q-learning)

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]\)

IQL (implicit Q-learning)

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.

🗄️ What the data doesn't say extrapolation · CQL · IQL

One state, a 1-D action. The logged actions (dots) cover only the middle. A degree-6 Q-network is fitted to them: plainly, with the CQL penalty, and with IQL's in-data policy extraction. The thin dashed curve is the true Q, which no method sees. Each method's chosen action is marked on the axis.

plain: true Q of its pick
—
CQL
—
IQL + AWR
—
Draw a few datasets. The plain fit often curls upwards at an edge where there is no data, and its argmax goes there, with a true value of zero. CQL bends those edges down; IQL never looks outside the data at all. The price is the same for both: they can't find a better action the data never tried, which is exactly what the online phase is for.

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:

$$a^{k-1}\sim\mathcal N\big(\mu_\theta(a^k,k,s),\ \sigma_k^2 I\big),\qquad \nabla_\theta J=\mathbb E\Big[\hat A(s,a^0)\sum_{k=1}^{K}\nabla_\theta\log\mathcal N\big(a^{k-1};\mu_\theta(a^k,k,s),\sigma_k^2\big)\Big]$$

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:

$$\pi_w(a\mid s)\ \propto\ \pi(a\mid s)\ \cdot\ p\big(I=1\mid s,a\big)^{\,w},\qquad I=\mathbb 1\big[\hat A(s,a)>\epsilon\big]$$

🧭 Ask for the good half advantage conditioning · guidance

Grasp offsets from 300 demonstrations: a careful operator (35%) and a sloppy one. Each attempt succeeded or failed. Behaviour cloning copies everything; the guided policy multiplies it by the learned probability of success, raised to the guidance weight w.

success, behaviour cloning
—
success, guided
—

🌫️ Policy gradient through the denoiser DPPO

A 6-step "diffusion" policy, pretrained to produce actions around 0 like its demonstrations. Each line is one sample's path from noise (left) to action (right). The reward sits at a = 1.3. Fine-tuning applies the policy gradient above to all six steps at once.

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.

Update-to-data ratio

Several gradient steps per robot step. Compute is cheap and robot time is not; LayerNorm and critic ensembles keep high ratios stable.

Reward from a classifier

\(r=\mathbb 1\big[c_\phi(o)>0.5\big]\), trained on a few hundred labelled success and failure images.

Collect, then infer

Riedmiller's framing: separate data collection from learning and keep every transition, so any later learner, on any objective, can reuse it.

⏱️ An hour of robot time demos · interventions · UTD

A real-robot run in miniature: a maze-like reaching task with a sparse reward, 10% slip, 0.5 s per step and a reset after every episode. The learner is off-policy Q-learning from replay. Pick a configuration and press run to add its curve; it averages three seeds. The x-axis is robot wall-clock time, including demos and resets.

From scratch the sparse reward is almost never found in 30 minutes. Interventions alone already get there; two demos do it faster; more updates per step faster still. Cut the reset time and everything speeds up, which is why so much real-robot RL engineering goes into automatic resets.

🧠 Quiz

Advanced · F

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:

$$\max_\theta\ J_r(\pi_\theta)\quad\text{s.t.}\quad J_c(\pi_\theta)=\mathbb E\Big[\sum_t\gamma^t c(s_t,a_t)\Big]\le d$$

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:

$$\mathcal L(\theta,\lambda)=J_r(\theta)-\lambda\,\big(J_c(\theta)-d\big),\qquad \theta\leftarrow\theta+\eta_\theta\nabla_\theta\mathcal L,\qquad \lambda\leftarrow\max\!\big(0,\ \lambda+\eta_\lambda\,(J_c(\theta)-d)\big)$$

Constraints that hold only on average are not enough for hardware, so a deployed system layers several mechanisms, from soft to hard:

In the policy

Action and torque limits, joint-limit and self-collision penalties, action-rate and energy terms, constrained RL for the expected costs.

Around the policy

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\).

Outside the software

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.

$$u^\text{safe}=\arg\min_u\ \lVert u-u^\text{RL}\rVert^2\quad\text{s.t.}\quad \nabla h(x)^\top f(x,u)+\alpha\,h(x)\ge0$$

⚖️ Let the multiplier find the penalty Lagrangian · dual ascent

A policy parameter θ trades task reward \(J_r=\theta-0.1\theta^2\) against a cost \(J_c=0.05\theta^2\) (say, mean contact force). Set the limit d and watch θ and λ settle; the dashed line is the true constrained optimum. Or switch to a fixed penalty and try to hit the limit by hand.

The multiplier overshoots, then settles exactly on the limit, for any d. A fixed penalty satisfies one particular limit only, and you find out which by trial and error. Raise the λ learning rate to see the classic Lagrangian oscillation, the reason practical versions add PID-style damping to λ.

🛡️ A safety filter on an RL policy control barrier function

The "RL policy" drives straight at the goal with exploration noise, through an obstacle it was never told about. The filter solves the QP above in closed form at every step: if the action would shrink the safe set too fast, it removes just the offending component. Four noise seeds per setting.

collisions (of 4)
—
closest approach
—
mean time to goal
—
Small α keeps a wide margin and costs time; large α lets the robot skim the surface. The filter never needs to know what the policy was trying to do, which is exactly why it works around a learned policy you can't fully trust. Its guarantee is only as good as the model inside it: here, the obstacle's position and the robot's dynamics.

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:

$$t_\text{loop}=t_\text{read}+t_\text{estimate}+t_\text{policy}+t_\text{write}\ \le\ T=\frac1{f_\text{ctrl}}\quad\text{every cycle},\qquad P(\text{miss})=P\big(t_\text{loop}>T\big)$$

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.

$$\hat w=s\cdot\operatorname{round}(w/s),\qquad s=\frac{\max|w|}{2^{b-1}-1},\qquad \mathbb E\big[(\hat w-w)^2\big]\approx\frac{s^2}{12}$$

⏲️ The control-loop budget deadline misses · jitter

4,000 simulated loop iterations. Each stage has a typical time and lognormal jitter, plus a rare OS hiccup. The VLA (≈45 ms) can run inside the loop or asynchronously. CPU load stretches every stage and makes hiccups more likely.

period
—
deadline misses
—
p99.9 loop time
—
With the VLA in the loop, every 50 Hz cycle misses. Make it asynchronous and the loop takes about 1.4 ms, of which the neural network is about 0.15. Now push the rate towards 1 kHz and add load: the average still fits, the tail doesn't. That tail is what real-time kernels, core isolation and watchdogs are for.

🔢 Precision vs parity quantisation · observation normalisation

A 2 → 16 → 1 network distilled from the capture-point balance controller of topic 15 keeps the inverted pendulum upright through three pushes. Quantise its weights, or feed it observations normalised with the wrong statistics, and see which one breaks it first.

result
—
mean |x|
—
This little controller survives INT8 and even INT4, and falls at INT3. But keep FP32 weights and simply forget the normalisation, or use statistics from an older training run, and it falls within two seconds. On real robots parity bugs are far more common than precision bugs, and they look exactly like this: a policy that was perfect in simulation, falling over on the first push.

✦The whole stack, in one table

Problem on a real robotToolTopic
Sim and robot disagreeSystem ID, domain randomisation, actuator models, history-based adaptation5, 11
Copying a demonstrator driftsDAgger, noise injection, RL on the policy's own states6
Data is free (simulation)PPO with GAE, thousands of parallel environments, curricula7, 10, 13
Data is expensive (hardware)SAC / MPO / RLPD, demos, interventions, high update-to-data ratio8, 18, 20
Sparse or unnatural behaviourPotential-based shaping, motion imitation (DeepMimic, AMP, trackers)4, 14
The robot sees less than the simulatorAsymmetric actor-critic, teacher–student distillation11
Reasoning is slow, balance is fastVLA on top, RL whole-body controller underneath, PD targets at 1 kHz12, 15
A good controller is almost good enoughResidual RL; RL fine-tuning of diffusion policies and VLAs17, 19
Learned policies can't be fully trustedConstrained RL, safety filters, watchdogs and e-stops21
It has to run, every cycle, on the robotAsynchronous slow models, fixed-rate loops, parity checks, quantise the big model only22

🧠 Quiz

Review

Cheat sheet & flashcards

Click a card to flip it. Try to recall the equation before you look.

Bellman expectation equation for v_πCh. 3
\(v_\pi(s)=\sum_a\pi(a|s)\sum_{s',r}p(s',r|s,a)[r+\gamma v_\pi(s')]\)
Bellman optimality for q*Ch. 3
\(q_*(s,a)=\sum_{s',r}p(s',r|s,a)[r+\gamma\max_{a'}q_*(s',a')]\)
Value iteration backupCh. 4
\(v_{k+1}(s)=\max_a\sum_{s',r}p(s',r|s,a)[r+\gamma v_k(s')]\)
Policy improvement theoremCh. 4
If \(q_\pi(s,\pi'(s))\ge v_\pi(s)\ \forall s\) then \(v_{\pi'}(s)\ge v_\pi(s)\ \forall s\).
Constant-α MC updateCh. 5
\(V(S_t)\leftarrow V(S_t)+\alpha[G_t-V(S_t)]\). The target is the full return, so there is no bootstrapping.
Weighted importance samplingCh. 5
\(V(s)=\dfrac{\sum_{t\in\mathcal T(s)}\rho_{t:T(t)-1}G_t}{\sum_{t\in\mathcal T(s)}\rho_{t:T(t)-1}}\)
TD error δCh. 6
\(\delta_t=R_{t+1}+\gamma V(S_{t+1})-V(S_t)\). The MC error is a sum of TD errors: \(G_t-V(S_t)=\sum_k\gamma^{k-t}\delta_k\) (if V is held fixed).
Q-learning updateCh. 6
\(Q(S,A)\leftarrow Q(S,A)+\alpha[R+\gamma\max_aQ(S',a)-Q(S,A)]\). It is off-policy and learns q* directly.
Semi-gradient TD(0)Ch. 9
\(\mathbf w\leftarrow\mathbf w+\alpha[R+\gamma\hat v(S',\mathbf w)-\hat v(S,\mathbf w)]\nabla\hat v(S,\mathbf w)\)
TD fixed point (linear)Ch. 9
\(\mathbf w_{TD}=\mathbf A^{-1}\mathbf b\), with \(\mathbf A=\mathbb E[\mathbf x_t(\mathbf x_t-\gamma\mathbf x_{t+1})^\top]\) and \(\mathbf b=\mathbb E[R_{t+1}\mathbf x_t]\)
Policy gradient theoremCh. 13
\(\nabla J(\boldsymbol\theta)\propto\sum_s\mu(s)\sum_aq_\pi(s,a)\nabla\pi(a|s,\boldsymbol\theta)=\mathbb E_\pi[G_t\nabla\ln\pi(A_t|S_t,\boldsymbol\theta)]\)
Softmax eligibility vectorCh. 13
\(\nabla\ln\pi(a|s,\boldsymbol\theta)=\mathbf x(s,a)-\sum_b\pi(b|s,\boldsymbol\theta)\mathbf x(s,b)\)

🗺️ How it all fits together

MethodLearnsTargetOn/off-policyChapter
Policy / value iterationv_π, v*expected one-step backup (model)—4
MC prediction / ES controlV, QG_ton5
Off-policy MCQρ · G_toff5
TD(0)VR + γV(S′)on6
SarsaQR + γQ(S′,A′)on6
Q-learningQ → q*R + γ max Q(S′,·)off6
Expected SarsaQR + γ Σπ Q(S′,·)either6
Gradient MC / semi-grad TDv̂(s,w)G_t / R + γv̂(S′,w)on9
Semi-gradient Sarsaq̂(s,a,w)R + γq̂(S′,A′,w)on10
REINFORCE (+baseline)π(a|s,θ)G_t (− b(s))on13
Actor–criticπ(a|s,θ) + v̂(s,w)δ = R + γv̂(S′) − v̂(S)on13 (draft 11)