Model-Based Reinforcement Learning
Imagine training a robot to fold laundry. A model-free agent must physically attempt millions of folds. It feels every failure before learning anything useful. A child, by contrast, can imagine folding a shirt in their head. They can predict that a certain grip will cause it to slip. They adjust before ever touching fabric. This capacity to simulate consequences internally, rather than by trial alone, is the animating idea behind model-based reinforcement learning (MBRL). In real systems — robotics, chip design, industrial control — every real interaction with the environment is expensive, slow, or risky. A drone that crashes to learn a control policy destroys hardware. A recommender system that "explores" badly loses user trust. Model-based RL addresses this by learning an explicit model of the environment's dynamics. This is a function that predicts the next state and reward given the current state and action. That model is then used either to plan directly or to generate additional synthetic experience for a model-free learner. This decouples the number of real environment interactions from the number of updates the agent can perform. Often the decoupling spans orders of magnitude. The big picture is a trade: model-free methods such as Deep Q-Networks (DQN) and policy gradients learn value functions or policies directly from real transitions. They require no assumptions about dynamics but demand enormous amounts of data. Model-based methods invest effort in learning a transition model and reward model . They then exploit that model computationally — via planning, rollouts, or gradient-based trajectory optimization. This squeezes far more learning signal out of each real transition. The price is that model errors compound over long horizons. A wrong model can mislead the agent as confidently as a correct one guides it. This article builds the concept from the ground up. It covers how a dynamics model is learned and represented. It explains how the model is used for planning and for generating synthetic ("imagined") rollouts. It examines the sample-efficiency and error-propagation trade-offs. It also includes a worked numerical trace. This trace shows exactly how model error accumulates over a multi-step rollout. It closes by connecting to the tree-search and planning methods. Model-based agents ultimately rely on these for deep, structured lookahead.
- MBRL learns an explicit dynamics model (and reward model) instead of, or alongside, a value function or policy.
- The model can be used for planning (search/optimize over imagined trajectories) or for Dara-Dyna-style synthetic experience to train a model-free learner faster.
- Sample efficiency is the main payoff: real transitions are reused via the model, sometimes cutting environment interactions by 10–100×.
- The core risk is compounding model error: small one-step prediction errors grow roughly exponentially with rollout horizon.
- Classic algorithms include Dyna-Q, PILCO, MBPO, and world-model agents like Dreamer, each managing the model-error trade-off differently.
- MBRL is a foundation for planning algorithms such as Monte Carlo Tree Search, which use a (learned or given) model to look ahead explicitly.
Learn how the world changes, then think before you act — trading extra computation for far fewer costly real-world trials.
The idea
A Markov decision process is defined by states , actions , a transition function , a reward function , and a discount . Model-free methods like Deep Q-Networks (DQN) never estimate or explicitly; they learn or a policy directly from sampled transitions . Model-based RL instead fits approximations and — collectively "the model" — from observed transitions, and then uses this model computationally, without needing new real interactions, to improve the policy. There are two broad ways to exploit a learned model. The first is planning: at decision time (or in the background), the agent uses the model to simulate candidate action sequences and picks the one with highest predicted return, using techniques such as random shooting, the cross-entropy method, model-predictive control (MPC), or tree search. The second is background planning / Dyna-style learning: the model generates synthetic transitions that are fed into an ordinary model-free update (e.g., Q-learning or an actor-critic update), effectively multiplying the amount of training data available per real environment step. Many modern systems blend both: they plan short rollouts to pick actions, and also use the model to generate extra training targets. The central quantity governing whether any of this is worthwhile is model bias and how it compounds. If the one-step prediction error of the model is (in some suitable metric, e.g., total variation distance between and ), then the error in a -step rollout's state distribution grows, in the worst case, linearly to quadratically in for small , and can be much worse if the model is used to roll out a changing policy trained partly on its own hallucinations — the so-called distribution shift problem, since the model is only accurate on states the real environment actually visits. Managing this compounding error — via short rollout horizons, uncertainty-aware ensembles, or model-predictive replanning — is the defining engineering challenge of MBRL, and separates naive approaches from state-of-the-art ones like MBPO and Dreamer.
How it works
Step 1 — Collect real data. The agent interacts with the true environment using some (possibly exploratory) policy, storing transitions in a replay buffer .
Step 2 — Fit the dynamics model. A parametric model , typically a neural network (feedforward, recurrent, or a latent-variable "world model"), is trained by supervised learning to predict (or the delta ) and from , minimizing a loss such as negative log-likelihood under a Gaussian output distribution:
Predicting a distribution (mean and variance) rather than a point estimate lets the agent quantify its own uncertainty, which is crucial for controlling compounding error. Many systems fit an ensemble of such models to capture epistemic uncertainty (disagreement between models) in addition to aleatoric uncertainty (the predicted variance of each model).
Step 3 — Use the model. Two families of usage:
- Planning / control: Sample or optimize action sequences by rolling them forward through and scoring cumulative predicted reward; execute the first action; replan at the next step (Model Predictive Control, MPC). Trajectory optimizers such as the Cross-Entropy Method (CEM) or gradient-based shooting methods are typical optimizers.
- Background data generation (Dyna-style): From states in , sample short synthetic rollouts of length using and the current policy, add these synthetic transitions to a separate buffer , and train the policy/value function with an off-the-shelf model-free algorithm using a mix of real and synthetic data.
Step 4 — Iterate. Because the policy changes, and because the model was only trained on old data, the model must be periodically re-fit on newly collected real transitions, and the loop repeats. This outer loop — collect real data, fit model, plan or generate synthetic data, improve policy, collect more real data — is the skeleton of essentially every MBRL algorithm. ```text Algorithm: Generic Model-Based RL (Dyna-style, e.g., MBPO) Input: real env E, policy π_φ, model ensemble {P̂_θ^1,...,P̂_θ^B}, rollout length k, real buffer D_real, model buffer D_model initialize π_φ, model ensemble θ, D_real ← ∅, D_model ← ∅ for iteration = 1, 2, ... do
# ---- (A) collect real experience ---- for t = 1..N_real do a ← π_φ(s) # possibly with exploration noise s', r ← step(E, s, a) D_real ← D_real ∪ {(s,a,r,s')} s ← s' end for
# ---- (B) fit dynamics model on REAL data only ---- for epoch = 1..E_model do sample minibatch B ⊂ D_real update θ by gradient descent on negative log-likelihood loss end for
# ---- (C) generate synthetic rollouts (background planning) ---- for m = 1..N_rollouts do s0 ← sample a real state from D_real # start on-distribution s ← s0 for step = 1..k do # SHORT horizon: caps error a ← π_φ(s) pick model j uniformly from ensemble # or aggregate ensemble s', r ← P̂_θ^j(s, a) # sample from predicted distribution D_model ← D_model ∪ {(s,a,r,s')} s ← s' end for end for
# ---- (D) improve policy with model-free updates on mixed data ---- for update = 1..N_policy_updates do sample minibatch from D_model (mostly) and D_real (some) update π_φ, value/Q functions via SAC / Q-learning / actor-critic step end for end for ``` For pure planning agents (no policy network at all, e.g., PETS), step (D) is replaced by direct action selection: ```text Algorithm: Model Predictive Control with a learned model (e.g., PETS) at each real time step t with current state s_t: initialize a distribution over action sequences a_{t:t+H} (e.g., mean/std for CEM) for CEM iteration = 1..M do sample P candidate action sequences from the distribution for each candidate sequence: roll it forward through the model ensemble from s_t (optionally average predictions over ensemble members, or sample a different member per particle, to hedge against model error) compute predicted cumulative reward refit the distribution to the top-E elite sequences by predicted return end for execute only a_t, the FIRST action of the best sequence observe real s_{t+1}; append (s_t,a_t,r_t,s_{t+1}) to D_real; replan next step ``` The "replan every step, execute only the first action" pattern is the essence of MPC: it bounds how far the agent trusts its own model before checking back against reality.
Complexity & correctness
Time and space. Let or feature dimension denote state size, action size, the number of ensemble models, the planning horizon, the number of candidate action sequences per CEM iteration, and the number of CEM iterations.
- Model training: one gradient step over a minibatch costs for a feedforward network — essentially standard neural-network training cost, independent of environment complexity beyond .
- Planning at each real step (MPC/CEM): each rollout of horizon requires forward passes through the model; there are candidates per CEM iteration and refinement iterations, so per real environment step planning costs model forward passes (the factor if evaluating the full ensemble per step, though many implementations sample one ensemble member per particle to keep cost ). This is paid per real time step, so it trades wall-clock compute for real-world sample efficiency — the central bargain of MBRL.
- Dyna-style background rollouts: generating synthetic trajectories of length costs model evaluations, but this is far cheaper than real environment steps whenever real interaction (physical time, robot wear, simulator cost) dominates a single neural-network forward pass — the typical regime in robotics and industrial control.
- Space: an ensemble of networks costs ; the synthetic buffer can be kept small (short rollouts, frequently overwritten) since stale synthetic data becomes increasingly wrong as the policy changes, unlike real data which remains ground truth forever.
Why the loop is correct (in the limit). If and (the model converges to the true dynamics and reward, which happens under standard supervised-learning consistency conditions given enough diverse real data and sufficient model capacity), then: 1. Any planning procedure that computes expected return under over horizon converges to the optimal -step lookahead policy under the true MDP, by continuity of the Bellman expectation operator in and . 2. Any policy-improvement step performed on synthetic data drawn from is, to first order, equivalent to performing that same step on real data, so Dyna-style updates converge to the same fixed point as pure model-free learning, but require far fewer real samples to reach a given model accuracy, since the same real transition informs both the model fit and any downstream planning.
The honest caveat — compounding model error. The convergence argument above hinges on on the states the agent actually visits. But the model is trained on states visited by past policies, while planning/rollouts query it on states induced by the current, changing policy — a distribution-shift problem structurally identical to the one in imitation learning. A useful bound (informal): if the per-step total-variation model error is bounded by , and the model is used to roll out steps under a policy whose value function has per-step reward bounded by , then the return-difference between planning in the model versus the real environment is bounded by
reflecting that model error accumulates quadratically with rollout length in the worst case (each of the steps can compound errors from all previous ones). This is the formal justification for two dominant design choices in modern MBRL: (a) keep synthetic rollouts short (MBPO typically uses – steps, always starting from real states) so error stays small, and (b) replan frequently in MPC so the agent never commits to a long open-loop plan whose errors have had time to compound; it only trusts the model's very first predicted step before checking reality again.
Worked example
Consider a 1-D "cart on a frictionless line" toy control task: state is position and velocity ; action is applied force; true dynamics are , ; reward is (stay near the origin). Suppose the learned model has a small systematic bias: it predicts correctly for velocity, but slightly overestimates position sensitivity: (an 10% overestimate — a modest, realistic learned-model error). Start at , and apply a constant corrective action for 5 steps in both the true environment and the model, to see how far predictions diverge.
| True | True | Model | Model | ||
|---|---|---|---|---|---|
| 0 | 1.000 | 0.000 | 1.000 | 0.000 | 0.000 |
| 1 | 1.000 | −0.050 | 1.000 | −0.050 | 0.000 |
| 2 | 0.995 | −0.100 | 0.9945 | −0.100 | 0.0005 |
| 3 | 0.985 | −0.150 | 0.9834 | −0.150 | 0.0016 |
| 4 | 0.970 | −0.200 | 0.9669 | −0.200 | 0.0031 |
| 5 | 0.950 | −0.250 | 0.9449 | −0.250 | 0.0051 |
Even though the velocity prediction is exact at every step (the model has zero error there), the position error accumulates every step because each step's position update depends on the velocity accumulated from all previous (slightly mis-integrated) positions through the coupled dynamics — this is compounding error in miniature. Over only 5 steps the divergence is small (0.005), but the position error grows roughly linearly here because the bias is a constant multiplicative factor on velocity's contribution to position; in higher-dimensional, nonlinear, chaotic dynamics (e.g., contact-rich robotic manipulation), the same mechanism produces errors that grow much faster, often practically exponentially, over just tens of steps. This is precisely why an MBRL agent using this model for MPC with replanning every step would only ever act on the prediction (error ) before re-measuring the real state, while an agent naively planning an open-loop 5-step trajectory in the model and executing it blindly would end up off in position — small here, but the qualitative lesson generalizes: short-horizon, frequently-corrected use of a model is dramatically more robust than long-horizon open-loop trust in it.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Long open-loop planning horizons | Model error compounds roughly quadratically with horizon; a model that looks great one-step-ahead can be useless 50 steps out | Replan every real step (MPC); keep synthetic rollouts short (e.g., ) |
| Ignoring model uncertainty | A point-estimate model looks confident even where it has never seen data, silently misleading the planner into exploiting model errors | Use ensembles or Bayesian models; penalize high-disagreement regions or use pessimistic (lower-confidence-bound) planning |
| Training the model only on on-policy data from a stale policy | The current policy visits new states the model was never trained on, so its predictions there are unreliable — a distribution-shift failure | Continually re-collect real data and refit the model every iteration; never freeze the model for long |
| Treating synthetic data as equally trustworthy as real data | Synthetic transitions inherit the model's bias; overweighting them lets errors dominate policy updates | Cap the fraction of synthetic data per batch; anneal it down if the model's validation error is high |
| Confusing "model accuracy" with "policy improvement" | A model can have low prediction MSE yet still cause bad planning decisions if errors are concentrated in reward-relevant directions | Evaluate the model by downstream planning/control performance, not just held-out prediction loss |
| Reward model mis-specification | Some pipelines assume reward is a known function of state and forget to also learn when reward is not directly observable from state alone | Explicitly fit jointly with , and validate it separately |
Pioneers & history
Origins · 1 minRichard S. Sutton and how this was discovered
Sutton introduced the Dyna framework in 1990, the first systematic proposal to interleave real experience, model learning, and model-generated "planning" updates within a single unified value-function learning loop, directly foreshadowing the model-free/model-based hybrids used today.
Where this matters
Model-based RL underlies systems where real-world trials are expensive or dangerous. In robotics, MPC with learned dynamics models lets manipulators and legged robots adapt to new objects or terrain within minutes rather than days of trial and error. In industrial process control (chemical plants, HVAC, data-center cooling), learned dynamics models allow safe, sample-efficient optimization without risking costly real-world failures during exploration. In autonomous driving simulation pipelines, learned world models are used to generate vast amounts of synthetic driving scenarios for training and stress-testing perception-to-control stacks. Game-playing agents such as MuZero extend the model-based idea by learning a model not of raw observations but of value-relevant abstract dynamics, which it then searches with a variant of Monte Carlo Tree Search — showing how a learned model, once available, naturally invites the kind of explicit lookahead planning that model-free agents cannot perform. The Dreamer family of agents demonstrates that agents can be trained almost entirely "in imagination," inside a learned latent world model, before ever touching the real environment again — the logical extreme of the sample-efficiency argument that motivates MBRL in the first place.
Ask the tutor: How does the MBPO algorithm formally bound the number of synthetic rollout steps needed to guarantee policy improvement over pure model-free learning?
Is model-based RL always more sample-efficient than model-free RL?
Usually, but not universally. MBRL tends to win decisively when real interactions are expensive relative to computation (robotics, industrial control), and when the true dynamics are relatively smooth and learnable from modest data. It can lose when the dynamics are extremely high-dimensional, chaotic, or hard to model accurately (e.g., contact-rich physics, stochastic multi-agent environments), because a poor model actively misleads the planner rather than helping it. In such cases, model-free methods with good exploration can outperform a biased model. The strongest modern systems (MBPO, Dreamer) are explicitly engineered to hedge this trade-off via short rollouts, uncertainty estimation, and continual model refitting.
How is a dynamics model actually represented — is it always a neural network?
Not always. Classical approaches used Gaussian processes (as in PILCO), which give principled, calibrated uncertainty estimates but scale poorly with data size. Modern deep MBRL typically uses feedforward or recurrent neural networks predicting a Gaussian (or mixture) distribution over the next state and reward, often as an ensemble of several independently trained networks to capture epistemic uncertainty. Latent world-model approaches (World Models, Dreamer, MuZero) instead learn a compressed latent representation of the state and predict dynamics entirely within that latent space, which is far cheaper to roll out than predicting raw high-dimensional observations like images.
What is the difference between planning and background planning (Dyna)?
Planning at decision time means the agent explicitly searches or optimizes over simulated trajectories using the model right before choosing the next real action — as in MPC/CEM. Background planning (Dyna-style) instead uses the model to generate extra synthetic transitions offline, which are fed into a standard model-free learning update (Q-learning, actor-critic) exactly as if they were real data. The agent's action selection at run time may then be as simple as querying a learned Q-function or policy network, with no explicit search happening at that moment. Many modern systems combine both: Dyna-style training to improve a policy/value network, plus occasional short-horizon MPC-style lookahead for extra decision-time refinement.
Why does model error compound, and can anything fully eliminate it?
Compounding happens because each predicted state feeds into the next prediction; a small error at step shifts the input to the model at step , which was never exactly the state the model was trained near, so its error there can be larger, and this effect accumulates across the horizon. Nothing fully eliminates this in principle — any imperfect model rolled out far enough will diverge from reality. Practical mitigations include keeping rollouts short, replanning frequently against real observations (MPC), using uncertainty-aware planning that avoids high-disagreement regions, and continually refitting the model on freshly collected real data so it stays accurate near the states the current policy actually visits.
How does MBRL relate to Monte Carlo Tree Search and planning more broadly?
A learned dynamics model is exactly the ingredient that classical planning algorithms like Monte Carlo Tree Search need but that pure model-free RL lacks: a way to simulate "what happens if I take this action" without touching the real environment. Once an agent has a reasonably accurate model, it can, in principle, apply any planning algorithm developed for known-model settings (dynamic programming, tree search, trajectory optimization) directly on top of the learned model. MuZero is the clearest example: it learns an internal, value-relevant model and then plans over it using MCTS, achieving strong performance without ever being given the true environment dynamics.
What is the "reality gap" and how does it relate to MBRL?
The reality gap refers to differences between a simulated model (or simulator) and the true environment it approximates — the same phenomenon that plagues sim-to-real transfer in robotics. In MBRL the learned dynamics model plays the role of this simulator, and the reality gap manifests as compounding prediction error whenever the agent's policy or actions push it into regions the model was never trained on. Techniques developed for sim-to-real transfer, such as domain randomization and uncertainty-aware policies, are directly analogous to the ensemble-based and short-horizon techniques used to manage a learned model's reality gap in MBRL.