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 P^(s′∣s,a)\hat{P}(s'|s,a) and reward model R^(s,a)\hat{R}(s,a). 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.

Key takeaways
  • MBRL learns an explicit dynamics model P^(s′∣s,a)\hat{P}(s'|s,a) (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.
The core insight

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 ss, actions aa, a transition function P(s′∣s,a)P(s'|s,a), a reward function R(s,a)R(s,a), and a discount γ\gamma. Model-free methods like Deep Q-Networks (DQN) never estimate PP or RR explicitly; they learn Q(s,a)Q(s,a) or a policy π(a∣s)\pi(a|s) directly from sampled transitions (s,a,r,s′)(s,a,r,s'). Model-based RL instead fits approximations P^θ(s′∣s,a)\hat{P}_\theta(s'|s,a) and R^θ(s,a)\hat{R}_\theta(s,a) — 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 ϵ\epsilon (in some suitable metric, e.g., total variation distance between P^\hat P and PP), then the error in a kk-step rollout's state distribution grows, in the worst case, linearly to quadratically in kk for small ϵ\epsilon, 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 (st,at,rt,st+1)(s_t, a_t, r_t, s_{t+1}) in a replay buffer Dreal\mathcal{D}_{\text{real}}.

Step 2 — Fit the dynamics model. A parametric model P^θ(s′∣s,a)\hat P_\theta(s'|s,a), typically a neural network (feedforward, recurrent, or a latent-variable "world model"), is trained by supervised learning to predict st+1s_{t+1} (or the delta st+1−sts_{t+1}-s_t) and rtr_t from (st,at)(s_t,a_t), minimizing a loss such as negative log-likelihood under a Gaussian output distribution:

L(θ)=E(s,a,s′,r)∼Dreal[−log⁡P^θ(s′∣s,a)−log⁡R^θ(r∣s,a)].\mathcal{L}(\theta) = \mathbb{E}_{(s,a,s',r)\sim\mathcal{D}_{\text{real}}}\Big[-\log \hat P_\theta(s'|s,a) - \log \hat R_\theta(r|s,a)\Big].

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 BB 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 at:t+Ha_{t:t+H} by rolling them forward through P^θ\hat P_\theta 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 Dreal\mathcal{D}_{\text{real}}, sample short synthetic rollouts of length kk using P^θ\hat P_\theta and the current policy, add these synthetic transitions to a separate buffer Dmodel\mathcal{D}_{\text{model}}, 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.

Figure
Model-based RL loop: real data, learned model, and two ways to use it
Real Environment E Replay buffer D_real Dynamics model P̂(s'|s,a), R̂(s,a) (ensemble) Planning / MPC CEM rollout search (pick a_t) Synthetic rollouts D_model (imagined transitions) Policy π_φ / Value fn Q_φ (model-free update) store (s,a,r,s') fit on real data simulate train on act π_φ inside rollout execute a_t state for planning

Complexity & correctness

Time and space. Let ∣S∣|S| or feature dimension dsd_s denote state size, dad_a action size, BB the number of ensemble models, HH the planning horizon, PP the number of candidate action sequences per CEM iteration, and MM the number of CEM iterations.

  • Model training: one gradient step over a minibatch costs O(batch size×(ds+da)×width)O(\text{batch size} \times (d_s+d_a) \times \text{width}) for a feedforward network — essentially standard neural-network training cost, independent of environment complexity beyond ds,dad_s,d_a.
  • Planning at each real step (MPC/CEM): each rollout of horizon HH requires HH forward passes through the model; there are PP candidates per CEM iteration and MM refinement iterations, so per real environment step planning costs O(M⋅P⋅H⋅B)O(M \cdot P \cdot H \cdot B) model forward passes (the BB factor if evaluating the full ensemble per step, though many implementations sample one ensemble member per particle to keep cost O(M⋅P⋅H)O(M\cdot P\cdot H)). 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 NrolloutsN_{\text{rollouts}} synthetic trajectories of length kk costs O(Nrollouts⋅k)O(N_{\text{rollouts}} \cdot k) model evaluations, but this is far cheaper than kk 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 BB networks costs O(B×network size)O(B \times \text{network size}); the synthetic buffer DmodelD_{\text{model}} 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 P^θ→P\hat P_\theta \to P and R^θ→R\hat R_\theta \to R (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 arg⁡max⁡\arg\max expected return under P^θ,R^θ\hat P_\theta,\hat R_\theta over horizon HH converges to the optimal HH-step lookahead policy under the true MDP, by continuity of the Bellman expectation operator in PP and RR. 2. Any policy-improvement step performed on synthetic data drawn from P^θ≈P\hat P_\theta \approx P 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 P^θ≈P\hat P_\theta \approx P 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 ϵ\epsilon, and the model is used to roll out kk steps under a policy whose value function has per-step reward bounded by Rmax⁡R_{\max}, then the return-difference between planning in the model versus the real environment is bounded by

∣ Jmodel−Jreal ∣  ≤  2Rmax⁡ ϵ k(k−1)2=O(ϵ k2),|\,J_{\text{model}} - J_{\text{real}}\,| \;\le\; \frac{2 R_{\max}\, \epsilon\, k(k-1)}{2} = O(\epsilon\, k^2),

reflecting that model error accumulates quadratically with rollout length in the worst case (each of the kk steps can compound errors from all k−1k-1 previous ones). This is the formal justification for two dominant design choices in modern MBRL: (a) keep synthetic rollouts short (MBPO typically uses k=1k=1–1515 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 ss is position xx and velocity vv; action a∈[−1,1]a\in[-1,1] is applied force; true dynamics are vt+1=vt+0.1atv_{t+1}=v_t+0.1a_t, xt+1=xt+0.1vtx_{t+1}=x_t+0.1v_t; reward is rt=−xt2r_t=-x_t^2 (stay near the origin). Suppose the learned model has a small systematic bias: it predicts v^t+1=vt+0.1at⋅(1.0)\hat v_{t+1}=v_t+0.1a_t\cdot(1.0) correctly for velocity, but slightly overestimates position sensitivity: x^t+1=xt+0.11vt\hat x_{t+1}=x_t+0.11v_t (an 10% overestimate — a modest, realistic learned-model error). Start at x0=1.0,v0=0.0x_0=1.0, v_0=0.0, and apply a constant corrective action at=−0.5a_t=-0.5 for 5 steps in both the true environment and the model, to see how far predictions diverge.

ttTrue xtx_tTrue vtv_tModel x^t\hat x_tModel v^t\hat v_t∣xt−x^t∣\lvert x_t-\hat x_t\rvert
01.0000.0001.0000.0000.000
11.000−0.0501.000−0.0500.000
20.995−0.1000.9945−0.1000.0005
30.985−0.1500.9834−0.1500.0016
40.970−0.2000.9669−0.2000.0031
50.950−0.2500.9449−0.2500.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 t=0→1t=0\to1 prediction (error 0.0000.000) 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 0.0050.005 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

PitfallWhy it happensFix
Long open-loop planning horizonsModel error compounds roughly quadratically with horizon; a model that looks great one-step-ahead can be useless 50 steps outReplan every real step (MPC); keep synthetic rollouts short (e.g., k≤15k\le15)
Ignoring model uncertaintyA point-estimate model looks confident even where it has never seen data, silently misleading the planner into exploiting model errorsUse 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 policyThe current policy visits new states the model was never trained on, so its predictions there are unreliable — a distribution-shift failureContinually re-collect real data and refit the model every iteration; never freeze the model for long
Treating synthetic data as equally trustworthy as real dataSynthetic transitions inherit the model's bias; overweighting them lets errors dominate policy updatesCap 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 directionsEvaluate the model by downstream planning/control performance, not just held-out prediction loss
Reward model mis-specificationSome pipelines assume reward is a known function of state and forget to also learn R^\hat R when reward is not directly observable from state aloneExplicitly fit R^θ(s,a)\hat R_\theta(s,a) jointly with P^θ\hat P_\theta, and validate it separately

Pioneers & history

Origins · 1 minRichard S. Sutton and how this was discovered
RS
Richard S. Sutton
1948– · University of Alberta; co-author of the standard RL textbook and originator of the Dyna architecture

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.

History
1990
— Richard Sutton introduces the Dyna architecture, unifying learning, planning, and acting with a learned model.
1998
— Sutton and Barto formalize model-based RL and planning within the standard reinforcement learning textbook framework.
2011
— PILCO (Deisenroth & Rasmussen) uses Gaussian-process dynamics models with uncertainty-aware planning for extremely sample-efficient robotic control.
2018
— PETS (Chua et al.) combines probabilistic ensembles with trajectory sampling (MPC), formalizing uncertainty-aware model-based control at scale.
2019
— MBPO (Janner et al.) proves and demonstrates that short model-based rollouts branched from real states can match or exceed model-free sample efficiency with strong asymptotic performance; World Models (Ha & Schmidhuber) and later Dreamer popularize learning compact latent "world models" for planning entirely inside a learned latent space.

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 tt shifts the input to the model at step t+1t+1, 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.

Before this

Where this leads