When you can run a model but not take its derivative, you plan by trial. Throw plans at a wall with one narrow gap. Blind darts find it only some of the time. A planner that refits to its best plans finds a clean path in a few rounds.
Pick a planner and press Plan. Each one gets the same 8 rounds of 48 tries. Then we build, piece by piece, the replanning loop, the three samplers, and the uncertainty that keeps a planner honest when the model is learned.
You need what a mean, a variance and a Gaussian are and a little Python. Part 1 helps but is not required. We build the rest from zero.
Lecture 14 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Before: Lecture 13, Part 1 (LQR, iLQR, SQP). Next: Lecture 15, Deep Model-Based RL.
Illustrative toy. A plan is 10 moves of at most 0.26 m each. The cost adds effort, a penalty for every point inside the wall, and 6 times the squared miss distance at the end. Each press uses new random draws, so results vary from press to press.
Chapter 0
Plan with a model you can run but cannot differentiate, by sampling, scoring and refitting
A warehouse robot must reach a shelf behind a wall. Its only model of the world is a physics simulator. You give the simulator ten moves, and it tells you where the robot ends up and what that cost. It gives no formula and no derivative.
Part 1 used calculus: LQR and iLQR follow the slope of the cost downhill. Here that fails three ways. A simulator with contacts has no slope you can trust. A neural network model is a black box. A wall makes the cost flat everywhere except at its edge, where it jumps.
So use the one cheap question you have: what happens if I try this plan? A rollout runs one plan through the model and returns its total cost. Planning by rollouts is a loop:
Press the three steps in order. Faint paths are samples, purple paths are the best 6, the bold path is the centre of the cloud.
Illustrative toy, the same field as the hero. The planner never sees the wall's shape. It only gets back one cost number per path.
No line of code says “go through the gap”. The cloud finds it because paths through the gap score better. This is sampling-based planning: it needs a model you can run, not one you can differentiate.
The symptom is a gradient planner that stalls on flat cost or chatters at a wall. To measure it, print the cost gradient along the plan: it is zero in free space and huge at the edge. The fix is to sample instead of differentiate.
Chapter 1
Wrap any planner in model predictive control, so that each new measurement corrects the plan
A cart must reach a mark and hold still while gusts push it. You plan the next minute perfectly. After one second a gust moves the cart. The rest of the plan now fits a cart that is no longer there.
Model predictive control (MPC), also called receding-horizon control, accepts this. At every step it measures the true state, plans H steps ahead, runs only the first action, and throws the rest away. H, the planning horizon, is short, so each plan is cheap.
What does each short plan minimise? Call the state at step k xk and the action uk. Call the cost of one step c. The plan cannot see past step t + H, so we add a terminal cost V: a guess of the cost from wherever the plan ends.
J equals the sum over k from t to t plus H minus one of c of x-k and u-k, plus V of x at t plus H.
Start from the measured state x-t. Roll the plan's actions u-k through the model for H steps and add each step cost c. Add V at the end state. That total is J. Run only u-t, then measure and plan again.
With made-up numbers: x-t = 2, the model is x-next = x-k + u-k, c = x² + u², V = x², H = 2. Plan (−1, −1): J = (4 + 1) + (1 + 1) + 0 = 7. Plan (−1.2, −0.4): J = 5.44 + 0.80 + 0.16 = 6.4, the best. Run −1.2. A gust of +0.3 leaves the cart at 1.1, not 0.8, so the next plan starts from 1.1.
Both carts start 2 m from the yellow mark and face the same gusts. Turn up the gusts and press New gusts.
Illustrative toy with the numbers above: x-next = x + u + gust, c = x² + u², H = 2. The plan-once cart computes all 40 actions at step 0 for a world with no gusts. The replanning cart solves the 2-step problem exactly at every step.
The plan-once cart drifts with the sum of the gusts. The MPC cart pulls back each step, because each new plan starts from the measured state. So MPC is closed-loop. The inner planner can be iLQR from Part 1, or any sampler in the next chapters.
The symptom is a short-horizon robot that stops in front of an obstacle it cannot see past. To measure it, plot the cost of the executed path against H. The fix is a better terminal cost V, often a learned value function, so that a short H still sees the future.
Chapter 2
Sample many plans from a fixed cloud, keep the cheapest, and count how often a narrow gap gets hit
Inside each MPC step we must find a cheap plan without gradients. The simplest way is random shooting: draw N plans at random, roll out each one, and keep the one with the lowest cost.
The data flow is the template for every sampler in this lesson. A plan is H actions. N plans form an array of shape N × H × (action size). Each rollout returns one cost, so N plans give N costs. Random shooting takes the smallest. The N rollouts do not depend on each other, so a GPU runs them at the same time.
Green paths pass through the gap. Narrow the gap or cut N and press Throw.
Illustrative toy. The hit rate p of one dart is measured on 4,000 extra throws for each gap width. The chance line uses the formula below.
How likely is at least one hit? Call the share of plan space that works p, the hit rate of one dart. Call the number of darts N.
P-hit equals one minus, one minus p, to the N.
The chance that one dart misses is 1 minus p. The darts are independent, so all N miss with chance 1 minus p, to the N. Subtract that from 1 to get P-hit.
With made-up numbers: p = 0.01 and N = 100 give P-hit = 1 − 0.99100 = 0.63. N = 300 gives 0.95. Now take a 10-step plan where each step must pick the right one of two turns. Then p = 0.510 ≈ 0.001, and 1,000 darts give only 0.62.
That last number is the weakness. The good region shrinks fast as the plan gets longer, and random shooting learns nothing between rounds. Every round draws from the same blind cloud.
The symptom is a planner whose best cost stops falling while N grows. To measure it, log the share of rollouts that score better than the current plan; near zero means blind darts. The fix is to move the cloud toward the darts that scored well. That is the next chapter.
Chapter 3
Keep a Gaussian cloud of plans and move it onto its own best samples, round after round
An archer shoots a volley. She looks at her best three arrows, aims at their average, and narrows her spread to match theirs. Volley by volley, the group closes on the bullseye. That is the cross-entropy method (CEM).
CEM keeps a Gaussian cloud of plans with a mean μ (mu), the current best guess, and a spread σ (sigma) for each action. Each round it samples N plans, scores them, and keeps the K cheapest. These are the elites. Then it refits μ and σ to the elites only. CEM throws the rest away.
Each dot is one plan, drawn as an aim point. Purple dots are the elites. Press Iterate. Then switch on the second goal and watch the mean.
Illustrative toy with 60 samples per round. The cost is the distance to the nearest goal. The ellipse shows 2 σ on each axis.
Here is the mean update. Call the set of elites E, its size K, and elite plan number k u(k).
Mu-new equals one over K, times the sum over k in E of u-k.
Sort the N plans by cost. Keep the K cheapest as the set E. Average those plans u-k, one action at a time. The average is mu-new.
With made-up numbers, for a one-number plan: the elites are 2.0, 2.6 and 3.1, so K = 3. Mu-new = (2.0 + 2.6 + 3.1) / 3 = 2.57. The cloud's centre jumps to where the winners landed.
The spread σ gets the same treatment: it becomes the spread of the elites, which sit close together. So the cloud shrinks as it moves. When σ is tiny, μ is the plan.
The symptom is a mean that lands between two good plans, in the bad region. Switch on the second goal: elites on both sides average to the middle. To measure it, compare the cost at μ with the best elite's cost. The fix is a larger elite share for early rounds, or a floor on σ, so that the cloud keeps exploring before it collapses.
Chapter 4
Push six numbers through sample, score, select and refit, and watch the mean move and the spread shrink
We search for one number u. The cost is C(u) = (u − 3)², so the best u is 3. CEM does not know that. It can only ask for C. It starts with a wide cloud, μ = 0 and σ = 2. It samples N = 6 and keeps K = 3.
Press Next step four times. Then press Next round to let CEM continue with fresh draws.
The first round uses the six fixed draws below, chosen for easy arithmetic. Later rounds draw at random from the refitted Gaussian.
| Sample u | −1.0 | 0.5 | 1.5 | 2.5 | 3.5 | 5.0 |
|---|---|---|---|---|---|---|
| Cost (u − 3)² | 16.0 | 6.25 | 2.25 | 0.25 | 0.25 | 4.0 |
The three lowest costs are 0.25, 0.25 and 2.25, so the elites are 2.5, 3.5 and 1.5. Their mean is μ-new = 7.5 / 3 = 2.5. Now the spread. Call the new variance σ²new: the average squared distance of the elites from μ-new.
Sigma-squared-new equals one over K, times the sum over k in E of u-k minus mu-new, squared.
For each elite u-k, take its distance from mu-new and square it. Average the squares over the K elites. That is sigma-squared-new.
The distances are −1, 0 and +1. Sigma-squared-new = (1 + 0 + 1) / 3 = 0.667, so σ = 0.82. In one round the mean moved from 0 to 2.5 and the variance fell from 4 to 0.667, six times smaller.
Run it again from μ = 2.5, σ = 0.82 and the mean creeps toward 3 while σ keeps falling. In the lab below, you write those two lines.
The symptom is a cloud that collapses after two rounds onto a plan that is not the best. To measure it, log σ and the best cost per round: σ near zero while the cost is still high means premature collapse. The fix is to keep σ above a floor or add a little noise each round.
Chapter 5
Replace the elite cut with a weight that falls off with cost, and tune how sharp it is with a temperature
CEM makes a hard cut: an elite counts fully, a sample one place lower counts zero. MPPI (model predictive path integral control) makes it soft. Every sample gets a weight. Cheap samples weigh a lot, costly ones almost nothing. The new plan is the weighted average.
Call the cost of sample i Ci and the sample itself u(i). A temperature λ (lambda) sets how fast the weight falls as the cost rises.
Mu-new equals the sum over i of e to the minus C-i over lambda, times u-i, divided by the sum over j of e to the minus C-j over lambda.
For each sample, compute e to the minus C-i over lambda. Divide each by their total, so the weights add to 1. Multiply each sample u-i by its weight and add. That is mu-new.
With made-up numbers: samples 3, 2 and 1 with costs 0, 1 and 4, and λ = 1. Raw weights 1, 0.368 and 0.018; divided by their total 1.386, they are 0.72, 0.27 and 0.01. Mu-new = 0.72 × 3 + 0.27 × 2 + 0.01 × 1 = 2.71. With λ = 0.25 it is 2.98; with λ = 4 it is 2.29.
Purple bars are the weights of 24 samples. The bold marker is MPPI's new plan. Drag λ, then switch on CEM's top 6 to compare.
Illustrative toy: 24 samples drawn evenly at random from −3 to 4, cost (u − 3)². The slider moves λ on a log scale from 0.05 to 20.
Small λ puts almost all weight on the cheapest sample, like keeping the best. Large λ gives every sample about the same weight, so the plan barely moves. MPPI runs inside MPC: after each step it shifts the plan by one step to warm-start the next solve. Williams and colleagues (2017) used it with a neural network model to drive a small rally car hard on dirt.
The symptom is a plan that jitters from step to step, or one that never moves. To measure it, compute the effective sample size: 1 divided by the sum of squared weights. Near 1 means λ is too small; near N means too large. The fix is to scale λ to the spread of the costs.
Chapter 6
Fit a model to robot data, see the planner chase its mistakes, and measure what the model does not know
So far someone handed us the model. Usually nobody does. So we learn it: run the robot, log each (state, action, next state), and fit a model f-theta that predicts the next state. Planning with it is model-based reinforcement learning (MBRL). The prize is sample efficiency: thousands of imagined rollouts for each minute of real robot time.
The danger is model exploitation. The planner looks for the plan the model says is cheapest. Where the model has no data, its predictions are arbitrary. If one of them is too good to be true, the planner finds it and drives there. A better planner finds it faster.
Blue dots are data. The dashed warm curve is the true reward, which the planner never sees. Switch between one model and an ensemble, and stretch the data.
Illustrative toy. Each model is a cubic fitted by least squares; the ensemble fits 5 cubics to 5 resamples of the data. The ensemble planner scores each action by the mean prediction minus 1.5 times the spread.
Where data is dense, the five models agree. Where it is missing, they fan out. Name the five predictions at an input x fb(x), their average f̄(x), and the count B. Their disagreement is the variance across members.
Sigma-squared-epi of x equals one over B, times the sum over b of f-b of x minus f-bar of x, squared.
Ask each of the B models for its prediction f-b at x. Average them to get f-bar. Square each member's distance from f-bar and average the squares. A large result means the models disagree, so nobody knows.
With made-up numbers and B = 3: near the data the predictions are 1.0, 1.2 and 0.8, so the disagreement is 0.027. Far from it they are 0.5, 2.0 and 3.5, so it is 1.5, about 56 times larger.
| Uncertainty | What it is | More data removes it? | How to capture it |
|---|---|---|---|
| Aleatoric | Noise in the world itself: sensor noise, slip. | No. | Each model predicts a mean and a variance. |
| Epistemic | The model's ignorance where it has little data. | Yes. | Disagreement across an ensemble. |
The symptom is a plan that looks great in imagination and fails on the robot. To measure it, compare predicted and real cost for each executed plan, and log the ensemble's disagreement along it. The fix is to make the planner pay for epistemic uncertainty. The next three chapters do that three ways.
Chapter 7
Model the dynamics with a Gaussian process, so that uncertainty raises the expected cost of a plan
PILCO (Deisenroth and Rasmussen, 2011) learns a cart-pole swing-up from a handful of real trials. Its rule: never let the model be overconfident.
Its model is a Gaussian process (GP): a distribution over functions that fit the data. Near data the GP is sure and its error bars are thin. Far from data it says “I don't know”, and the bars widen. PILCO pushes a Gaussian over the state through the GP, step by step, and approximates each result as a Gaussian again (moment matching). The predicted cost is then a smooth formula of the policy's parameters, so PILCO follows its exact gradient.
Why do error bars stop exploitation? Take one step. The robot will land at a point with predicted mean m and standard deviation s. The goal is g, and the cost is the squared miss, (x − g)². Average that cost over where the robot may land:
The expected value of c equals m minus g, squared, plus s squared.
Take the miss of the predicted mean, m minus g, and square it. Add the variance s squared. The sum is the expected cost. Two plans with the same mean are not equal: the less certain one costs more.
With made-up numbers, goal g = 1.0 m. Plan A: m = 0.9, s = 0.05, so E[c] = 0.01 + 0.0025 = 0.0125. Plan B: m = 1.0, s = 0.4, so E[c] = 0 + 0.16 = 0.16. Plan B aims dead on, but its uncertainty makes it 13 times costlier.
The pink band is the GP's guess of where each action lands, ± 2 s. The planner picks the action with the lowest expected cost. Press Run a trial.
Illustrative toy: a 1-D GP with a squared-exponential kernel (length 0.8, signal 1, noise 0.01) and two starting data points. Each trial runs the chosen action on the true curve and adds the result.
Each trial lands close to the goal, because the planner avoids actions whose landing it cannot predict. That is why PILCO needs so few trials. The price: a GP's cost grows with the cube of the number of data points, and its usual kernel assumes smooth dynamics. A foot striking the ground is not smooth.
The symptom is training that slows to a crawl after a few thousand transitions, or poor fits at contacts. To measure it, time each model update and plot the GP's error at contact events. The fix is to swap the GP for neural networks that scale. That is PETS.
Chapter 8
Score each plan by many particles that hop between ensemble members, so that disagreement raises the cost
PETS (probabilistic ensembles with trajectory sampling; Chua and colleagues, 2018) keeps PILCO's care about uncertainty but uses neural networks. The name lists its two parts.
The probabilistic ensemble is B = 5 networks. Each predicts a mean and a variance for the next state; that variance captures aleatoric noise. Each trains on its own resample of the data, so their disagreement captures epistemic uncertainty. One ensemble covers both rows of the table in Chapter 6.
Trajectory sampling turns the ensemble into one cost. Start P particles at the current state. At each step, each particle uses one ensemble member and samples a next state from that member's prediction. The plan's cost is the average over particles. Where members agree, particles stay together. Where they disagree, particles scatter, and the scattered ones are often expensive.
The plan pushes the robot right at a constant speed. Data covers states up to the blue line; beyond it the five members disagree. Drag the push.
Illustrative toy. Member b adds a drift d-b times (x − 1)² beyond x = 1, with d-b spread from −0.6 to 0.6. The cost is the squared distance from the goal at step 10, averaged over particles.
A worked number. Four particles end with costs 1, 1, 1 and 9. The particle average is 3. A single model that predicts the mean path might say 1. PETS charges 3, so a plan that wanders into unknown states looks risky, not free.
PETS wraps this in MPC: at each real step it runs CEM over plans, scores each by trajectory sampling, and runs the first action. On the half-cheetah task, the paper reports reaching the performance of soft actor-critic with 8 times fewer samples and of PPO with 125 times fewer.
The symptom is a PETS agent that is too timid to try anything new. To measure it, plot particle spread along executed plans and the reward over trials. If the spread never shrinks, the agent avoids collecting the data that would shrink it. The fix is to give it more data near its plans: each real trial does that.
Chapter 9
Branch short imagined rollouts off real states, and feed them to a model-free learner
MBPO (model-based policy optimization; Janner and colleagues, 2019) does not plan with the model. It uses the model as a data factory for a model-free learner such as soft actor-critic. Its title asks the question: when to trust your model?
Its answer is: for a few steps. A learned model has a small error after one step. The next step starts from a slightly wrong state, and the error grows. Call the model's error per step ε (epsilon), the factor by which the dynamics stretch an old error each step L, and the rollout length k.
E-k equals epsilon times, one plus L plus L squared and so on, up to L to the k minus one.
Each step adds a new error epsilon. Each later step stretches every old error by L. Add the newest error, the one before times L, the one before that times L squared, and so on for k steps. That is e-k.
With made-up numbers: ε = 0.01 m and L = 1.2. One step: 0.01 m. Five steps: 0.074 m. Twenty steps: 1.87 m. Short rollouts stay near the truth; long ones are fiction.
The blue trunk is real data. Pink branches are rollouts in the model; the warm dashes show where the true system would go. Drag the branch length k.
Illustrative toy with ε = 0.01 and L = 1.2 per step, as in the worked number. The branch error is the formula above. The drawing shows 1 m of error as 60% of the canvas height and clips larger errors.
So MBPO starts each rollout from a real state the robot visited: a branched rollout. It keeps k short and uses a PETS-style ensemble so the learner cannot exploit one model. The cheap synthetic data lets the learner take many more updates per real step: the paper uses 20 to 40.
The symptom is a policy whose returns in imagination climb while real returns fall. To measure it, compare model-predicted and real next states on held-out real data, at 1, 5 and 20 steps. The fix is a shorter k, raised slowly only as the model's error falls.
Chapter 10
Keep the terms, the numbers, the checklist and the core code in one place
Plan with a model you can only run: sample plans, roll them out, score them, refit, and run the first action inside MPC. When the model is learned, the planner will exploit its errors, so make it pay for what the model does not know.
| Method | How costs become an update | Number to remember |
|---|---|---|
| Random shooting | Keep the cheapest of N. | P-hit = 1 − (1 − p)N: p = 0.01, N = 100 gives 0.63. |
| CEM | Mean and variance of the top K. | Elites 1.5, 2.5, 3.5: μ 0 to 2.5, σ² 4 to 0.667. |
| MPPI | Weights e−C/λ, weighted average. | Costs 0, 1, 4 at λ = 1: weights 0.72, 0.27, 0.01. |
| Method | Model | How the model is used | Uncertainty rule |
|---|---|---|---|
| PILCO (2011) | Gaussian process | Closed-form prediction, exact policy gradient | Variance adds to expected cost |
| PETS (2018) | 5 probabilistic networks | CEM inside MPC, particles score plans | Disagreement scatters particles |
| MBPO (2019) | Probabilistic ensemble | Short branched rollouts train a model-free learner | Short k caps compounding error |
CEM inside MPC, for any model you can roll out. U has shape H × action size.
pythonimport numpy as np def rollout_cost(model, cost, x0, U): # U: (H, du) x, J = x0, 0.0 for u in U: J += cost(x, u); x = model(x, u) # the planner only calls the model return J def cem_plan(model, cost, x0, mu, sigma, N=64, K=8, iters=5, floor=0.02): for _ in range(iters): S = mu + sigma * np.random.randn(N, *mu.shape) # (N, H, du) samples C = np.array([rollout_cost(model, cost, x0, U) for U in S]) E = S[np.argsort(C)[:K]] # the K elites mu, sigma = E.mean(0), np.maximum(E.std(0), floor) return mu, sigma def mpc_step(model, cost, x, mu, sigma): mu, sigma = cem_plan(model, cost, x, mu, sigma) u0 = mu[0] # run only the first action mu = np.vstack([mu[1:], mu[-1:]]) # warm-start: shift by one step return u0, mu, np.ones_like(sigma) * sigma.max()
Course credit: Lecture 14 of Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page.
Papers: PILCO, Deisenroth and Rasmussen (ICML 2011). PETS, Chua, Calandra, McAllister and Levine (NeurIPS 2018). MBPO, Janner, Fu, Zhang and Levine (NeurIPS 2019). MPPI for aggressive driving, Williams and colleagues (ICRA 2017).