Model-Based RL
Learn the dynamics, then plan through them with last lecture's tools. Levine builds the algorithm in versions — 0.5 fails from distributional shift, 1.0 fixes it DAgger-style, 1.5 adds replanning (MPC) — then shows why the planner exploits an overconfident model, why epistemic (not aleatoric) uncertainty is the cure, and how bootstrap ensembles deliver it. The lecture closes with model-based RL from images via latent state-space models.
Why learn the model, and the naive recipe
The premise of model-based RL: if we had an estimate of the dynamics — a function , or stochastically — we could use all the planning tools from the previous lecture to control the system instead of doing model-free RL at all. Everything in this lecture learns only a model and plans through it; using models to learn policies comes next lecture.
The most obvious algorithm — Levine calls it model-based RL version 0.5, “not quite the thing you want to use” — is three steps. Run a basic exploration policy (uniformly random is fine) to collect transitions . Fit the dynamics by supervised learning:
(squared error being negative log-likelihood under a Gaussian; cross-entropy for discrete states). Then plan through to choose actions.
Does this work? Sometimes, very well: it is essentially how system identification works in classical robotics. There you already know the equations of motion and are fitting a handful of unknowns — masses, friction or drag coefficients — so if the true model is in your class, modest data pins down those few numbers (given a base policy that excites the system’s different modes). The recipe is effective precisely when you can hand-engineer the dynamics representation. With high-capacity models like deep nets, it breaks — for a reason we have seen before.
Distributional shift: DAgger for models
Picture trying to reach the top of a mountain. A random walk explores one slope, and from that data the model learns a very reasonable inference: the more right you go, the higher you get. Plan through that model and you walk right — off the far edge.
The data came from the state distribution induced by the base policy. But planning through is itself a policy — call it , not a network but a planning algorithm run on top of the model — with its own distribution . The problem is exactly that : the model is valid where went, but the planner seeks out the actions the model scores highest, those lead to states it was never trained on, it makes an erroneous prediction there, feeds it back into itself, and predicts something even more wrong at the next step.
The fix is borrowed from DAgger: collect more data where the learned object will actually operate. Here it is far easier than DAgger, because no human expert is needed — to label a state–action pair with its next state, you just take the action and watch nature. Version 1.0: learn the model, plan through it, execute those plans, append the resulting transitions to , retrain, repeat. “It’s essentially just like DAgger, only for models” — with the anachronistic caveat that this procedure long predates DAgger. In principle, version 1.0 works.
Replanning: model predictive control
But what if you make a mistake? Some mistakes are cliffs — sudden, unrecoverable — but many are not. Say your model predicts you’ll drive straight when the wheel is two degrees left. Execute the open-loop plan and you drift left, a little more each step, and stay wrong until retraining eventually fixes the model. We can learn faster by fixing mistakes as they happen: replan from the state you actually reached instead of the one the plan predicted.
The intuition for how to replan: “the more you re-plan, the less perfect each individual plan needs to be.” In practice people use much shorter horizons than for one open-loop plan, and even random shooting often works — last lecture’s closing demonstration was exactly MPC with a short horizon, leaning almost entirely on replanning. Homework 4 involves implementing essentially this procedure.
The planner exploits your model
So version 1.5 pretty much always works — but how well? In a Berkeley experiment on half-cheetah, version 1.5 with a deep-net model learned quickly but plateaued around reward 500 — moving forward, just slowly — while a model-free learner bootstrapped from it eventually reached about 5,000. Why the tenfold gap?
Iterative data collection poses a unique challenge: the model must not overfit early, when data is scarce, yet needs the capacity to do well later, when data is plentiful. Deep nets struggle in the low-data regime, so they do poorly early, which means poor exploration, which means getting stuck. And it is worse than ordinary overfitting:
Uncertainty estimation is the fix. Suppose you want to walk to the edge of a cliff for the view. If the model predicts a distribution over next states and you plan for expected reward, then near the edge — where the model is uncertain — substantial probability mass falls off the cliff and incurs a huge negative reward, so the planner automatically stays back. No explicit pessimism is engineered in; taking the expected value under an uncertain model already makes the planner hedge its bets across the possible worlds consistent with the data, and as data accumulates near the edge, uncertainty shrinks and it walks closer. Caveats Levine flags: you still need to explore (excess caution can keep you from high-reward regions forever), and the expected value is neither the pessimistic value (a lower confidence bound, reasonable for safety) nor the optimistic value (which favors exploration) — but it “is a pretty good place to start.”
Two kinds of uncertainty, and how to estimate the right one
The obvious idea — have the network output a distribution over (a softmax, or a Gaussian mean and variance) and use its entropy — is, Levine says flatly, “a bad idea; this does not work.” An overfitted model matches its training points almost exactly, so its optimal output variance is nearly zero: it will be extremely confident and completely wrong out of distribution. The entropy of the output is measuring the wrong thing.
Being uncertain about the model means being uncertain about the parameters . Instead of the usual , estimate the full posterior — its entropy is the model uncertainty — and predict by integrating the parameters out:
Done exactly, this is intractable for neural nets, so we approximate. Bayesian neural networks put a distribution over every weight; the common tractable approximation factorizes the posterior into independent marginals, with — each weight gets an expected value and an uncertainty. It’s crude (weights interact tightly), and training it needs variational inference, covered next week; see Blundell et al., “Weight Uncertainty in Neural Networks” and Gal et al., “Concrete Dropout”.
Today’s simpler method — which in Levine’s experience “actually works a little bit better” in model-based RL — is bootstrap ensembles: train many networks that agree on the training data but make different mistakes outside it, and let their disagreement measure uncertainty.
The approximation is crude — training ten nets costs ten times the compute, so ensembles usually have fewer than 10 members — but it is enough.
Planning under an uncertain model
Before, the planner optimized with . With models, choose the action sequence that maximizes the average reward over models:
The general recipe, for any candidate action sequence: sample (for an ensemble, pick one of the models at random); step it forward, sampling at each time step; sum the rewards; repeat and average. With a small ensemble you can sum over all models instead of sampling; fancier alternatives like moment matching over the state distribution exist. Then optimize over action sequences with your favorite method — random shooting or CEM — and run it all inside the version 1.5 MPC loop.
The approach transfers to the real world: a robotic hand with an ensemble-based model, learning directly from physical interaction, performs a full in-palm rotation of two objects after about three hours and does it reliably after four. For the foundations, Levine recommends PILCO (Deisenroth, ~2011) — Gaussian processes rather than neural nets, but one of the papers that established why epistemic uncertainty matters in model-based RL.
Model-based RL with images
What about image observations — Atari frames, a robot’s camera? Three obstacles: images are high-dimensional, which makes prediction hard; they are redundant; and they are usually partially observed — one frame of Breakout doesn’t tell you the ball’s velocity. So we adopt the POMDP model: dynamics over an unobserved state, and an observation model . The appealing separation of concerns: the observation model handles the high-dimensional stuff but no temporal dynamics; the latent dynamics handle time but stay low-dimensional. A reward model joins them, since reward depends on a state we never see.
With states observed we would maximize . With states latent, we need the expected log-likelihood under the posterior over states given the observations — as in hidden Markov models. So we learn an approximate posterior, the encoder , with a spectrum of choices: from a full smoothing posterior — most accurate, hardest to train — down to a single-step encoder , simplest and crudest, appropriate when the problem is nearly fully observed. Stochastic encoders need variational inference (next week); today’s limiting case is a deterministic single-step encoder, , a delta function that collapses the expectation entirely. Substitute it in:
The second term is an autoencoder — encode , reconstruct it back; the first forces encoded states to obey the learned dynamics; a reward term is added the same way. Everything is differentiable, so train it all jointly with backprop, and plug the result straight into version 1.5: collect tuples, train encoder + dynamics + reward + observation models, plan in latent space, execute the first action, replan.
Published instances: Embed to Control (Watter et al.) uses a stochastic encoder and LQR in the latent space — its learned embeddings visibly recover the 2D structure of a navigation task and the cyclic structure of a pendulum. A successor regularizes the latent space to be locally linear, making it ideal for iterative LQR, and runs on real robots: stacking Lego blocks and pushing objects from images, with a human supplying reward labels by keypress, after roughly 20 minutes of training — far more efficient than the model-free alternatives.
And one final twist: you can skip the latent space altogether and model dynamics directly in observation space, (with recurrence over past observations to handle partial observability). When the scene has dozens of objects and no obvious compact state, predicting pixels directly can work very well — a robot arm using such a model plans to move a designated image point to a target location, reaching out and pushing a stapler where it was told.
Check yourself
Conceptual and derivation exercises in the lecture’s spirit — work them before opening the solutions.
A colleague fits a deep-net dynamics model to 10,000 transitions collected with a random policy on a driving simulator, verifies a tiny held-out prediction error on transitions from the same policy, then plans through the model and reports the car does something absurd. (a) Explain precisely why the small held-out error did not predict planning performance, naming the two distributions involved. (b) Why would the same procedure likely have worked if the model were a known vehicle model with three unknown coefficients? (c) What is the minimal change to the algorithm that fixes the failure asymptotically?
Show solution
(a) The held-out set is drawn from , the state distribution of the random data-collection policy, so it certifies accuracy only there. Planning through the model defines a new policy with its own distribution , and the planner specifically selects actions whose predicted outcomes look best — steering toward states that are out of distribution, where errors are large and compound: an erroneous predicted state is fed back into the model, producing a still more erroneous one. Since , held-out error under says nothing about the states the planner actually visits. (b) With three physical coefficients, the hypothesis class is so constrained that if the true model lies in it, almost any exciting data pins the parameters down; the model then extrapolates correctly even off-distribution. This is classical system identification. Expressive models fit tightly to the training distribution and extrapolate arbitrarily badly. (c) Close the loop on data: plan through the model, execute those plans, append the resulting transitions to the dataset, retrain, and repeat (version 1.0 — DAgger for models). The training distribution then converges toward the distribution the planner induces.
Your model has a small systematic bias: executing its “drive straight” action actually turns the car 2 degrees left per step. Compare open-loop execution of a 50-step plan (version 1.0) against MPC (version 1.5) on this system. (a) Roughly how far off-heading is the open-loop car at the end? (b) Why does MPC largely eliminate the problem even without retraining the model? (c) Why can MPC get away with much shorter planning horizons and cruder optimizers like random shooting?
Show solution
(a) The heading error accumulates roughly linearly: about by the end — the car finishes nearly perpendicular to its intended direction, since the open-loop plan never consults the real state. (b) MPC executes one action, then observes the actual resulting state and replans from it. After one step the car is only 2 degrees off; the planner, starting from the true state, immediately compensates. The model is still wrong about the fine effect of small steering inputs, but once a deviation is large enough to matter, correcting it no longer requires a model accurate to within 2 degrees — the required correction is coarse. Errors are repeatedly zeroed out instead of integrated. (c) Because “the more you re-plan, the less perfect each individual plan needs to be”: each plan only has to be roughly right for one executed step before it is thrown away and recomputed. Mistakes in the tail of the horizon are never executed, so a short horizon and a noisy optimizer such as random shooting suffice — the closed loop supplies the precision the individual plans lack, at the price of planning at every time step.
For each scenario, state whether the relevant uncertainty is aleatoric or epistemic, whether collecting more data reduces it, and what a maximum-likelihood model that outputs a Gaussian would report there: (a) predicting the sum of two dice about to be rolled, after observing a million rolls; (b) predicting the next state at the edge of a cliff the agent has never approached; (c) an overfitted dynamics model evaluated exactly on its own training points.
Show solution
(a) Aleatoric: the world itself is random. More data does not reduce it — the sum of two dice stays a nondegenerate distribution forever. The ML model correctly reports a wide output distribution here; this is the one case output entropy gets right. (b) Epistemic: nothing is necessarily noisy about the cliff; the agent simply does not know which dynamics function is correct there because it has no data. More data (approaching gradually) shrinks it to zero. The ML model reports whatever its extrapolation happens to be, typically with confidently small — an erroneous mean and an erroneous variance, for the same reason: nothing trained the uncertainty head out of distribution either. (c) Neither, really — but the ML model reports near-zero variance, because on training points its means match the targets almost exactly, so zero variance maximizes likelihood. This is exactly why output entropy is the wrong tool: the model is maximally confident precisely where overfitting makes it least trustworthy off the training points. What is needed instead is the posterior — “the model is certain about the data, but we are not certain about the model.”
A two-model ensemble predicts the next (scalar) state as and . (a) Write the correct ensemble predictive distribution and contrast it with the “average the means” shortcut. (b) Compute the mean and variance of the correct predictive distribution. (c) A planner gets reward if the next state lands in and otherwise. Compare the expected reward under the correct mixture with the reward the averaged-mean prediction implies, and explain what this says about disagreement as an uncertainty signal.
Show solution
(a) The posterior is approximated as , so the predictive distribution is the mixture — two sharp bumps at . The shortcut averages the means into a single : one confident bump at a state neither model predicts. (b) Mixture mean: . Mixture variance, by the law of total variance: within-component variance plus between-component variance , giving — eleven times the shortcut’s variance. The disagreement between the models is the epistemic term. (c) Under the correct mixture, essentially all mass sits near , outside , so expected reward is close to . The averaged-mean Gaussian puts nearly all its mass inside the interval, promising reward close to . The shortcut manufactures confidence out of disagreement and would lure the planner into exactly the exploitation failure uncertainty estimation exists to prevent; mixing the probabilities keeps the hedge, so the planner correctly treats this action as unpromising in expectation.