Model-Based Reinforcement Learning

Learn a model of the world, then plan inside it. In this toy, a drone that imagines 10 steps ahead clears every gate that a 2-step planner hits, as long as it replans after each step.

Learn how a robot fits a model of its own dynamics, plans through it, and keeps the model's errors from piling up.

Press Fly. Slide the horizon down to 2 and fly again. Then raise the model error, switch replanning off, and watch the warm imagined path part from the real one. Then we build it piece by piece: the model, random shooting, CEM, MPC, compounding error, ensembles, Dyna and latent models.

You need a little Python and what a probability is. Q-learning helps in Chapter 7. We build the rest from zero.

Re-taught from the model-based RL lecture of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.

Fly the gates by imagining ahead

10 steps
0.40

Illustrative toy. The drone moves one column per step. Thrust from −1 to 1 changes its climb speed, against drag and gravity. The planner is CEM with 60 plans, 8 elites and 4 rounds, scored in the model. At error 1 the model overrates thrust by 50% and underrates gravity by 60%. With replanning off, the drone flies each whole plan before it plans again.

Chapter 0

Practise in Imagination

See why real robot time is the scarce resource, and how a learned model stretches it

A robot arm learns to stack blocks. Each try takes about 10 seconds: reach, grasp, lift, place, reset. Say the learner needs a million tries. That is 116 days of robot time for one skill.

A model-free learner, such as Q-learning or SAC, learns values or a policy straight from real tries. A model-based learner first learns a dynamics model: a function that predicts the next state from the current state and action. Then it practises inside that model, where a try costs microseconds and breaks nothing.

The model-based loop has four steps:

  1. Act in the real world. Record each transition: the state, the action and the next state.
  2. Fit the model to every transition recorded so far.
  3. Plan, or practise, inside the model.
  4. Act with the result, record more transitions, and go back to step 2.

Count the robot days

The faint bar is a model-free learner. The solid bar needs less data because it practises in a model. Change the tries and the seconds per try, and watch the bars against the one-week line.

1.0M
10 s

Arithmetic only. The data savings are knobs, not measurements. The PETS paper (Chua et al., 2018) reports model-free scores with many times fewer real samples on its benchmark tasks.

With 10 seconds a try, a million tries is 10 million seconds: 116 days. Ten times less data is 11.6 days. A hundred times less is under 28 hours, one long lab session.

The failure. The model is never exact, and a planner that trusts it walks into its mistakes. This is model bias. The symptom is a plan that scores well in the model and badly on the robot. Measure it: run the plan for real and compare its return with the model's prediction. Every chapter from 4 on is a fix for this.

The road

  1. Learn the dynamics: supervised learning on transitions, predicting the change.
  2. Random shooting: guess many plans, run them in the model, keep the best.
  3. The cross-entropy method: search near the plans that scored well.
  4. Model-predictive control: the hero's replanning switch, explained.
  5. Why model error compounds: the hero's horizon and error sliders, as a bound.
  6. Ensembles: let models disagree where data is missing.
  7. Dyna and short rollouts: imagined data for a model-free learner.
  8. When planning fools itself: exploitation, mismatch and compounding.
  9. Latent models and real robots: plan from pixels, and when to choose a model.
  10. The field guide: terms, numbers, a checklist and the core code.
What does a model-based learner gain, and what does it risk?

Chapter 1

Learn the Dynamics

Turn recorded transitions into a supervised learning problem, and predict the change instead of the next state

The arm's joints are at 1.20, 0.50 and 0.80 radians. You send a small motor command. Where are the joints 50 ms later? A dynamics model answers that question, one step at a time.

Training it is supervised learning: inputs with known answers. The input is a state s and an action a. The answer is the next state, s-prime. Every recorded transition is one training example.

Predict the change, not the next state. From one step to the next, a joint moves by about 0.01. A network that outputs the whole next state spends its effort copying the input. A network that outputs the delta, s-prime minus s, spends it on what changes. Then the next state is s plus the predicted delta.

Call the model f-θ (f-theta), where θ are its weights. Call the number of recorded transitions N.

Say it aloud

L of theta equals one over N times the sum over i of the squared length of s-prime-i minus s-i, minus f-theta of s-i and a-i.

L(θ)
L of theta the loss: how wrong the model is, averaged over the data.
1/N
one over N divide by the number of transitions, to get an average.
Σi
the sum over i one term for each recorded transition i.
s′i − si
s-prime-i minus s-i the true change in state for transition i.
fθ(si, ai)
f-theta of s-i and a-i the change the model predicts from that state and action.
‖ · ‖2
the squared length square each number of the state vector and add them up.
In plain words

For each transition, subtract the predicted change f-theta from the true change. Square the result and add over the state's numbers. Average over all N transitions. Gradient descent on theta lowers L.

With numbers

With made-up 1-D transitions: true changes 0.5, 0.6 and −0.3, predicted changes 0.4, 0.5 and −0.2. Each error is 0.1 in size, so each square is 0.01. L = (0.01 + 0.01 + 0.01) / 3 = 0.01.

Fit a model where the data is

Teal is the true change in state for each state, and the teal dots are the recorded transitions. Warm is the fitted model. Narrow the data range and watch the model guess outside it.

0.5 to 3.0
20

Illustrative: one state, one fixed action, true change 0.8 sin(1.3 s) + 0.15 s plus a little noise. The model is a degree-5 polynomial fitted by least squares, a stand-in for a small network.

pythonclass Dynamics(nn.Module):                  # state [B, ds], action [B, da]
    def __init__(self, ds, da, h=256):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(ds + da, h), nn.ReLU(),
                                 nn.Linear(h, h), nn.ReLU(), nn.Linear(h, ds))
    def forward(self, s, a):
        return s + self.net(torch.cat([s, a], -1))      # next state = s + predicted delta

loss = ((model.net(torch.cat([s, a], -1)) - (s2 - s)) ** 2).sum(-1).mean()  # L(theta)

The failure: distribution shift. You fit the model on data from random actions. The planner then steers the arm where random actions never went, and there the model guesses. The symptom: on fresh data from the planner, the model's error is far above its error on held-out training data. The fix: record what the planner does, add it to the data, refit, and repeat the loop.

A model fitted on random-action data plans well in the model but fails on the robot. What is the most likely cause?

Chapter 2

Plan by Random Shooting

Guess many action sequences, run each one through the model, and send the first action of the best one

You stand at position 3 on a line and want to reach 7. Each step you choose a velocity from −1 to 1. You have a model. Which first action should you take?

Random shooting answers by brute force. Guess many action sequences at random. Run each one through the model. Keep the sequence with the best total reward, and send only its first action to the robot. There is no policy network and no gradient.

A plan covers H steps, the planning horizon. It starts at the real state, called s-hat-0. Action a-k takes the model from imagined state ŝk (s-hat-k) to the next imagined state: ŝk+1 = ŝk + f-theta(ŝk, ak). A reward function r scores each imagined state.

Say it aloud

R of a-zero to a-H-minus-one equals the sum, for k from zero to H minus one, of r of s-hat-k-plus-one.

R(a0…aH−1)
R of the plan the score of one action sequence, measured in the model.
Σk=0H−1
the sum for k from zero to H minus one one term for each planned step.
r
r the reward of a state; here minus its distance to the goal.
ŝk+1
s-hat-k-plus-one the imagined state after action a-k.
In plain words

Start at the real state. Apply a-0 in the model to get s-hat-1, and score it with r. Apply a-1 to get s-hat-2, and score it. Add all H scores to get R.

With numbers

With the model “next position = position + action”, start 3, goal 7, H = 3. Plan [1, 1, 1] visits 4, 5, 6: R = −3 − 2 − 1 = −6. Plan [0.8, 0.5, −0.2] visits 3.8, 4.3, 4.1: R = −8.8. Plan [−0.5, 0.3, 0.1] scores −12.8. The robot takes velocity 1.

Shoot random plans at the goal

Each purple line is one random plan, imagined step by step downward. Warm is the best one, and the teal arrow is the only action the robot takes. Press Shoot, then change the number of plans.

30
3 steps

Illustrative: the model here is exact (position plus action, kept between 0 and 10), so you see the search alone.

The failure: too many dimensions. Say a random action is good enough half the time, in each dimension and at each step. With one dimension and 3 steps, 1 plan in 8 is good. With 7 motor dimensions and 10 steps, 1 in 2 to the 70 is good, about 8 × 10−22. The symptom: the best plan barely beats an average one. The fix: search near the plans that scored well, which is the next chapter.

Random shooting finds a best plan of 10 actions. How many of those actions does the robot carry out before it plans again?

Chapter 3

Search Smarter With the Cross-Entropy Method

Keep a bell curve over plans, and move it toward the plans that scored best

Random shooting forgets. After 100 guesses it knows roughly where the good plans are, then it guesses blind again. The cross-entropy method (CEM) keeps that knowledge in a Gaussian, a bell curve, over plans. Each round:

  1. Sample N plans from the Gaussian: a mean μ (mu) and a spread σ (sigma) for each planned action.
  2. Score each plan in the model.
  3. Keep the best M plans, the elites.
  4. Refit μ and σ to the elites. Repeat 3 to 5 times.
  5. Send the first action of the final mean to the robot.

Call the elite plans A-1 to A-M. Each one is a list of H actions.

Say it aloud

Mu becomes one over M times the sum, for j from one to M, of A-j.

μ
mu the mean plan: one number for each planned action.
←
becomes replace the old mean with the new value.
1/M
one over M divide by the number of elites.
Σj=1M
the sum for j from one to M add the elite plans together.
Aj
A-j elite plan number j.
In plain words

Add the elite plans action by action, and divide by M. That is the new mean mu. The new spread sigma is the standard deviation of the elites, action by action.

With numbers

With the device's task (start 3, goal 4.5, actions from −2 to 2, H = 2) and 6 made-up samples, the best two are (1.8, −0.5), scoring −0.5, and (1.2, 0.6), scoring −0.6. So mu = (1.5, 0.05) and sigma = (0.3, 0.55). A first step of 1.5 lands on the goal.

Shrink the bell curve onto good plans

Each point is a two-step plan: first action across, second action up. Darker blue scores higher. Purple dots are samples, ringed dots are elites, and the ellipse is the Gaussian. Press Next round.

Illustrative task with an exact model. Elites are the top 20% of each round. The best plan is (1.5, 0) or any first action of 1.5 with a second action near 0.

The failure: the bell curve shrinks too soon. If sigma falls near zero around a fair plan, CEM stops searching and never finds a better one. The symptom: all N samples are almost the same plan. Measure it by logging sigma after each round. The fix: keep a floor under sigma, sample more, or start from the last step's plan shifted by one step.

After one CEM round, the elites are (1.0, 0.2), (1.4, 0.0) and (1.6, 0.4). What is the new mean plan?

Chapter 4

Replan Every Step: Model-Predictive Control

Plan over a short window, take one action, look at the real world, and plan again

Your model believes in a tailwind that does not exist. You plan 8 steps to the goal and carry out all 8. You stop short, because the wind never pushed. What if you had looked again after one step?

Model-predictive control (MPC) plans over H steps, sends only the first action, observes the real next state, and plans again from there. The plan is a window that slides forward one step at a time. Each real observation resets the model's error to zero at the start of the next plan.

Choose how often to look again

Teal is the cart's real position over time. Each warm dashed line is one plan, as the model imagined it. Pick how many steps of each plan to carry out before you plan again.

Illustrative: the cart's speed decays by 30% a step and each action adds up to 0.6. The model adds a false push of 0.15 a step. The planner is CEM with 40 plans, 4 rounds and H = 8.

MPC pays for this in computation. Call the number of CEM rounds I, the plans per round N, and the horizon H.

Say it aloud

C equals I times N times H.

C
C the model steps spent to choose one real action.
I
I the number of CEM rounds.
N
N the plans sampled in each round.
H
H the steps in each plan, the horizon.
In plain words

Each round scores N plans, and each plan takes H model steps. Do I rounds. Multiply the three to get C for one real action.

With numbers

With I = 5, N = 500 and H = 10, C = 25,000 model steps for one action. At 20 actions a second, that is 500,000 model steps a second, so the model must be small and run in parallel.

The failure: a bias in every step. Replanning stops error from building up over a plan. It does not remove a mistake the model makes in every step, so the cart settles a little short and stays there. To measure it, average the predicted minus the real next state over many steps; a mean far from zero is a bias. The fix is to refit the model on the new data.

Why does MPC tolerate model errors that ruin a plan carried out in full?

Chapter 5

Why Model Error Compounds

Follow a small one-step error through a long imagined rollout, and bound how fast it grows

Your model is off by at most 0.01 in each step. After 20 imagined steps, how far off can it be? Not 0.2. With the numbers below, the worst case is 66.5.

Two things feed the error. First, the model adds a new mistake each step, at most ε (epsilon). Second, each step starts from the wrong state, and the world can stretch a starting gap. Call the most it stretches a gap in one step L, the Lipschitz constant of the true dynamics. Two states 0.1 apart are at most L × 0.1 apart one step later. Call the gap between the imagined and the real state after k steps e-k.

  1. After one step, the gap is the model's own mistake.
    e1 ≤ ε
  2. Step k+1 starts e-k away from the truth. The world stretches that to L times e-k, and the model adds up to ε more.
    ek+1 ≤ L ek + ε
  3. Unroll the rule H times. It gives epsilon times 1 + L + L² and so on, up to L to the H minus 1. That geometric series has a closed form.
    eH ≤ ε(1 + L + … + LH−1)
Say it aloud

e-H is at most epsilon times L to the H minus one, all over L minus one.

eH
e-H the gap between the imagined and the real state after H steps.
≤
is at most this is the worst case, not the usual case.
ε
epsilon the model's largest error in one step.
LH
L to the H the stretch factor L, multiplied by itself H times.
L − 1
L minus one from the geometric series; the formula needs L different from 1.
In plain words

Start with epsilon. At each step, multiply the gap so far by L and add epsilon again. After H steps the gap is at most this formula. If L is above 1, it grows like L to the H.

With numbers

With made-up epsilon 0.01 and L 1.5: the bound is 0.01 after 1 step, 0.025 after 2, 0.13 after 5, 1.13 after 10 and 66.5 after 20. With L = 1 it grows 0.01 a step. With L = 0.9 it never passes 0.1.

Grow the gap step by step

Each warm bar is the worst-case gap after that many imagined steps, on a log scale. Bars past the red line are as large as the state itself. Raise L, then the horizon.

0.010
1.50
10 steps

The bound for a deterministic model whose one-step error is at most epsilon everywhere, with true dynamics that stretch gaps by at most L. The line at 1 assumes states range over about 1 unit.

The failure: errors that agree. Real errors come close to the bound when they point the same way every step. A model that underrates friction predicts that the robot slides too far, every step. The symptom: long rollouts drift to one side. Measure it: run the model k steps along recorded real trajectories and plot the gap against k. The fixes: short rollouts, replanning, and training on multi-step predictions.

A model has one-step error epsilon 0.01, and the world has L = 2. What is the bound on the gap after 3 steps?

Chapter 6

Know Where the Model Is Unsure: Ensembles

Train several models, read their disagreement as a warning, and make the planner avoid it

One network gives one answer, even far from its data. So train K networks, each from a different random start and on a different resample of the data. Where the data is dense they agree. Where it is missing they disagree.

That disagreement measures epistemic uncertainty: uncertainty from missing data, which more data removes. Aleatoric uncertainty is noise in the world itself, such as a slippery floor, and data does not remove it. Call model number k f-k, and the average of the K predictions μ(s, a) (mu of s and a).

Say it aloud

Sigma squared of s and a equals one over K times the sum over k of the squared length of f-k of s and a, minus mu of s and a.

σ2(s,a)
sigma squared of s and a how much the models disagree about this state and action.
1/K
one over K divide by the number of models.
Σk
the sum over k one term for each model.
fk(s,a)
f-k of s and a model k's predicted next state.
μ(s,a)
mu of s and a the average of all K predictions.
In plain words

Ask all K models for the next state, and average them to get mu. Square each model's distance from mu, and average the squares. Its square root, sigma, is the spread.

With numbers

With made-up predictions near the data, 4.0, 4.2, 3.9, 4.1 and 3.8: mu = 4.0 and sigma = 0.14. Far from the data, 4.0, 6.5, 2.1, 5.2 and 3.0: mu = 4.16 and sigma = 1.56, eleven times larger.

Now use the spread as a warning. Call the planner's caution λ (lambda).

Say it aloud

R-tilde of s and a equals r of s and a minus lambda times sigma of s and a.

r̃(s,a)
r-tilde of s and a the cautious reward the planner scores with.
r(s,a)
r of s and a the reward the model predicts.
λ
lambda the caution: 0 means none.
σ(s,a)
sigma of s and a the ensemble spread from the equation above.
In plain words

Take the reward, and subtract lambda times the spread. Places where the models disagree now look worse to the planner.

With numbers

With lambda 1 and reward 5 at both places above: near the data, r-tilde = 5 − 0.14 = 4.86. Far from it, 5 − 1.56 = 3.44. The planner prefers the place it knows.

Make the planner fear disagreement

Thin warm lines are five models of the reward, and yellow is their spread. The dashed teal line is the real reward, which the planner cannot see. Purple marks the planner's pick. Raise the caution.

0.00

Illustrative: we drew the five curves; we did not train them. They agree near the data and spread with the square of the distance from it, as trained ensembles tend to do.

PETS (Chua et al., 2018) plans with this idea. To score a plan, it rolls out several particles. At each step, each particle uses a model picked at random. Plans whose particles scatter get uncertain returns, and CEM avoids them.

The failure: members that agree by accident. If every model trains on the same data from the same start, they share mistakes and the spread stays small where data is missing. Measure it: compare sigma with the real error on fresh data. The fix: a different random start and a bootstrap resample for each model.

Five models agree closely at state A and disagree widely at state B. What does that tell the planner?

Chapter 7

Imagined Data for a Model-Free Learner: Dyna and Short Rollouts

Replay transitions from the model as extra practice, and keep imagined rollouts short

MPC searches at every real step, which is costly at run time. The model has a second use: it can make extra training data for a model-free learner. The learner practises cheaply. At run time it needs only its policy, with no search.

Dyna (Sutton, 1991) does this with a table. After each real step, Dyna-Q updates its Q-values from the real transition and stores the transition in its model. Then it replays K remembered states and actions through the model, with the same update. Call the learning rate α (alpha) and the discount γ (gamma). The model returns a reward r and a next state s′ for state s and action a.

Say it aloud

Q of s and a becomes Q of s and a, plus alpha times: r, plus gamma times the max over a-prime of Q of s-prime and a-prime, minus Q of s and a.

Q(s,a)
Q of s and a the learner's estimate of the return after action a in state s.
α
alpha the step size, from 0 to 1.
r
r the reward, here predicted by the model.
γ
gamma the discount on the next step's value.
maxa′
the max over a-prime the value of the best action in the next state.
s′
s-prime the next state, here predicted by the model.
In plain words

Take a remembered state and action, and ask the model for r and s-prime. The target is r plus gamma times the best Q at s-prime. Move Q a fraction alpha of the way to the target.

With numbers

With made-up alpha 0.5 and gamma 0.95: Q(s,a) = 0, the model says r = 0, and the best Q at s-prime is 0.8. Q becomes 0 + 0.5 × (0 + 0.95 × 0.8 − 0) = 0.38, and no real step was spent.

Practise in the maze between steps

Left is the maze, with the learned route in teal. Right is the steps each episode took. Pick K, the imagined updates per real step, and press Run.

Illustrative: a 9 by 6 maze in the style of Sutton and Barto's Dyna maze. Alpha 0.1, gamma 0.95, epsilon-greedy 0.1, reward 1 at the goal. Each curve is the median of 9 runs.

MBPO (Janner et al., 2019) brings this to deep RL. It starts short model rollouts from real states in its data, and trains SAC on real plus imagined transitions. Chapter 5 says why short: with epsilon 0.01 and L 1.5, a 5-step rollout is off by at most 0.13, a 20-step one by 66.5. Starting from real states keeps each rollout near data the model knows.

The failure: imagined data becomes a lesson. MPC sees the real state every step. A Dyna learner trains on imagined transitions as if they were real, so a wrong one teaches a wrong value. The symptom: predicted returns climb while real returns stall. The fix: shorter rollouts, an ensemble, and a cap on the share of imagined data.

MPC can plan 30 imagined steps ahead, but MBPO keeps its rollouts to a few steps. Why?

Chapter 8

When Planning Fools Itself

See why a harder search against a wrong model finds a worse plan, and name the three failures that feed each other

Search harder and get a worse plan. Picture 1,000 candidate plans and a model with small random errors. The plan with the best predicted score is often the one whose error is the largest and positive.

This is model exploitation. The optimizer hunts for the model's mistakes, because a mistake that overrates a plan looks like a great plan. Plans far from the data are the most exposed, since the model's errors are largest there. A penalty on ensemble spread, from Chapter 6, pulls the search back toward the data.

Search harder, get fooled more

Left: one search, each purple dot a plan at its model score; plans to the right are farther from the data. Right: the average over many searches, what the model promises (warm) and what the winner pays (teal).

300
0.0

Illustrative: plans far from the data are worse in reality, and the model's error there is larger. Each curve point averages 150 searches. Caution subtracts lambda times the spread of a 5-model ensemble.

In this toy, with large error and no caution, a search over 1,000 plans promises about 4.8 and pays about −1.2. With caution 2, it promises 2.1 and pays 1.5: a smaller promise, kept.

Three failures feed each other. Objective mismatch: the model learns to predict every state well on average, but the planner needs it right only where the reward depends on it. Exploitation: the planner steers to where the model errs in its favour. Compounding: long rollouts carry each error forward and grow it.

FailureSymptomMeasureFix
Objective mismatchLow model loss, poor plansModel error on the states the planner visitsRefit on planner data; weight the states that decide reward
ExploitationPredicted return far above real returnModel return minus real return of the chosen planEnsemble penalty; keep plans near the data
CompoundingLong plans driftk-step error against kShort rollouts and replanning
You raise CEM from 500 to 5,000 plans per round. The predicted return rises and the real return falls. What happened?

Chapter 9

From Pixels: Latent Models and Real Robots

Compress camera frames to a short state, plan there, and decide when a model is worth it

A colour camera frame of 64 by 64 pixels holds 12,288 numbers. A model that predicts every pixel of the next frame is costly, and its predictions blur. A latent model first compresses each frame into a short vector z, the latent state. Then it learns the dynamics of z and predicts the reward from z.

Why does a pixel model blur? Trained with squared error, it predicts the average of the futures it cannot tell apart. If the ball may bounce up or down, the average is a faint ball in both places. A latent model with a random part in z can sample one future and decode a sharp frame.

Predict pixels, or predict a few numbers

A ball moves with an uncertain speed and bounces off the walls. Slide how far ahead to predict. Press Sample to draw another future from the latent model.

4

Illustrative: 16 by 16 frames and 9 equally likely speeds. The pixel model is the exact average of the 9 futures, the best a squared-error pixel model can do.

World Models (Ha and Schmidhuber, 2018), then PlaNet and Dreamer (Hafner et al.), follow this recipe. Dreamer trains its policy on imagined rollouts in latent space.

On a real robot with a state vector, a common first recipe uses every chapter so far:

  1. Record a few minutes of random actions.
  2. Train an ensemble of about 5 small networks to predict state changes.
  3. Control with MPC and CEM, replanning at the control rate.
  4. Add the new data, refit, and repeat until the success rate stops rising.
ChooseWhen
Model-basedReal data is costly; dynamics are smooth; the state is small or compressed
Model-freeSimulation is free; contact makes dynamics jump; you want the best final score

The failure: contact. Grasping and insertion change the dynamics in a jump, from not touching to touching. Smooth networks round the jump off. The symptom: plans that work in free space fail at contact. Measure the model error separately on contact and free-space steps. The fix: more data near contact, or a model with separate modes.

A pixel model trained with squared error predicts a faint ball in two places. Why?

Chapter 10

The Field Guide

Keep the terms, the numbers, a checklist and the core code on one page

Fit a model of the change in state from real transitions. Plan through it with CEM, take one action, and replan from the real state. Keep imagined rollouts short, because error grows like L to the H. Use an ensemble to see where the model is guessing, and penalise those places. Or replay the model's transitions to a model-free learner, from real states and for a few steps.

Terms and numbers

TermWhat it isNumber from this page
Dynamics modelPredicts the next state, best as s plus a predicted changeLoss 0.01 on three toy transitions
Random shootingBest of N random plans, first action only[1, 1, 1] scores −6 from 3 toward 7
CEMRefit a Gaussian to the elites, repeatMean (1.5, 0.05) after one round
MPCPlan H steps, act once, replan25,000 model steps per action at I 5, N 500, H 10
Error bounde-H ≤ ε(LH − 1)/(L − 1)0.13 at 5 steps, 66.5 at 20 (ε 0.01, L 1.5)
Ensemble spreadDisagreement of K models: missing data0.14 near data, 1.56 far from it
Cautious rewardr − λσ4.86 against 3.44 at λ 1
DynaK imagined Q-updates per real step0 to 0.38 in one imagined update
MBPOShort rollouts from real states, then SACRollouts of a few steps

Before you trust a model-based run

MPC with CEM, the core loop

pythonimport numpy as np

def cem_plan(model, reward, s, H=10, N=500, M=50, I=5, da=1, lam=0.0):
    mu, sd = np.zeros((H, da)), np.ones((H, da))
    for _ in range(I):
        A = np.clip(mu + sd * np.random.randn(N, H, da), -1, 1)  # N plans [N, H, da]
        x, R = np.repeat(s[None], N, 0), np.zeros(N)
        for k in range(H):
            preds = model(x, A[:, k])                  # ensemble: [K, N, ds]
            x = preds.mean(0)                         # mu(s, a)
            R += reward(x) - lam * preds.std(0).sum(-1)    # r - lambda * sigma
        elite = A[np.argsort(R)[-M:]]                  # best M plans
        mu, sd = elite.mean(0), elite.std(0) + 0.05    # refit, with a floor on sigma
    return mu[0]                                     # the first action only

for t in range(T):                                  # MPC: replan from the real state
    a = cem_plan(model, reward, s)
    s2 = env.step(a); data.append((s, a, s2)); s = s2
# every few episodes: refit each ensemble member on a bootstrap resample of data

Keep going

The takeaway. A model turns real data into cheap imagined practice. Its errors grow with every imagined step, so look at the real world often, keep rollouts short, and stay where your models agree.
Which change most directly stops a planner from steering into regions the model has never seen?

Now press Present or Teach and explain, from memory, why model error compounds and how MPC and short rollouts contain it. Then go back to the drone, set the error to 0.8, and fly with replanning off and then on.

Credit and source

This lesson re-teaches the model-based RL lecture of Stanford CS 224R: Deep Reinforcement Learning. The work behind it: Sutton (1991), Dyna; Chua et al. (2018), PETS; Janner et al. (2019), MBPO; Ha and Schmidhuber (2018), World Models; Hafner et al., PlaNet and Dreamer. The toys and numbers here are our own.

CS 224R: Model-Based Reinforcement Learning
The course site · PETS · MBPO · Back to Gleams