Sign in

MBPO

Model-Based Policy Optimization

Learn an ensemble model of the environment, branch short imagined rollouts from real states, and train the policy mostly on that imagined data.

Overview

Real experience is expensive and a learned model is cheap but imperfect. If you let a model imagine a long future, its small errors pile up and the policy learns to exploit a world that does not exist. MBPO keeps the imagination on a short leash. Every imagined rollout starts from a state the agent really visited and runs for only a few steps, so the model never drifts far from what it knows. Thousands of such short branches supply most of the policy's training data, and a small share of real data keeps it honest. This template is a small NumPy version that uses soft Q-learning over discrete actions where the original method uses Soft Actor-Critic.

A short history

Michael Janner, Justin Fu, Marvin Zhang and Sergey Levine at UC Berkeley published MBPO in 2019 in the paper When to Trust Your Model. Learned models had promised to save data, but their errors grow with every imagined step and mislead the policy. MBPO's answer was to keep imagined rollouts very short and to start them from real states, then train a Soft Actor-Critic agent on the result. It matched the final performance of model-free methods on standard locomotion benchmarks with far fewer real steps.

How it works

  1. collect takes steps_per_epoch real steps with the current soft policy and stores them in the real buffer.
  2. train_model fits each member of DynamicsEnsemble to predict the change in state and the reward. Each member sees its own bootstrap resample of the real data.
  3. rollout_model samples rollouts_per_epoch real states and steps each forward rollout_length times. Every step uses one randomly chosen member, and the results go to the model buffer.
  4. update_policy builds each batch from a small real share (real_ratio) and model data for the rest, and takes soft Q-learning steps on it.
  5. After every step the target Q network moves a fraction target_tau toward the trained one, which keeps the learning targets from shifting too fast.
  6. train repeats these four stages each epoch. act samples from the soft policy while learning and takes the best action when greedy=True.

Watch out for

  • A longer rollout_length gives more imagined data per real state, but each extra step is predicted from a predicted state, so model errors compound and the policy can learn from states that cannot occur.
  • A policy trained on model data will find and exploit any place where the model wrongly predicts high reward. Keeping some real data in each batch limits this but does not remove it.
  • The members here are deterministic networks trained with squared error, so the model cannot represent noise in the environment. The original method uses probabilistic members.
  • There is no termination model. On a task where episodes end early for a reason, such as falling over, the imagined rollouts would continue past the point where the real episode stops.
  • With the temperature α\alpha too small the soft policy is almost greedy and stops exploring. Too large and it stays close to random.

Use cases

When to use it

Use it when real environment steps are the scarce resource and you want a fast reactive policy at the end, with no planning at decision time. If the reward function is known and planning each step is affordable, PETS is simpler.

In industry

Robotics
Learning continuous control when real robot time is the limiting cost, by training mostly on short rollouts from a learned dynamics model.
Industrial control research
Tuning controllers for simulated plants or energy systems where each real experiment is slow or costly.
Research
A reference point for sample-efficient reinforcement learning on continuous control benchmarks.

Choosing it: what must hold

  • Dynamics smooth enough for a neural network ensemble to predict a few steps ahead from state vectors.
  • Real environment steps that are much more expensive than compute, because model training and imagined data add heavy computation.
  • Continuous actions, since the policy learner inside is Soft Actor-Critic.

When to choose something else

IfUse instead
Environment steps are cheapSAC or PPO directly, without a model
You would rather plan each action than learn a policyPETS
Observations are imagesWorld Models, which first compresses frames to a latent vector

Math foundations

  1. Fitting one ensemble member

    Li(ϕi)=1∣Di∣∑(s,a,r,s′)∈Di∥fϕi(s,a)−(s′−s,  r)∥2L_i(\phi_i) = \frac{1}{|D_i|} \sum_{(s, a, r, s') \in D_i} \big\lVert f_{\phi_i}(s, a) - (s' - s,\; r) \big\rVert^{2}

    Each member learns to predict the change in state and the reward. DiD_i is that member's own resample of the real data, which makes the members differ where data is thin. The template normalizes the targets and averages over output dimensions.

  2. A branched rollout

    s0∼Denv,at∼π(⋅∣st),(st+1,rt)=fϕit(st,at),t=0,…,k−1s_0 \sim D_{\text{env}}, \qquad a_t \sim \pi(\cdot \mid s_t), \qquad (s_{t+1}, r_t) = f_{\phi_{i_t}}(s_t, a_t), \qquad t = 0, \dots, k - 1

    Start from a real state, not from the start of an episode, and imagine only kk steps. The member iti_t is drawn fresh at every step, so one rollout mixes the opinions of the whole ensemble.

  3. The soft policy

    π(a∣s)=exp⁡ ⁣(Q(s,a)/α)∑bexp⁡ ⁣(Q(s,b)/α)\pi(a \mid s) = \frac{\exp\!\big(Q(s, a) / \alpha\big)}{\sum_{b} \exp\!\big(Q(s, b) / \alpha\big)}

    Better actions are more likely, but every action keeps some probability. The temperature α\alpha sets how strongly the policy prefers the best action.

  4. The soft state value

    V(s)=αlog⁡∑aexp⁡ ⁣(Qˉ(s,a)/α)V(s) = \alpha \log \sum_{a} \exp\!\big(\bar{Q}(s, a) / \alpha\big)

    A smooth version of the maximum over actions. It equals the expected Q value under the soft policy plus α\alpha times the policy's entropy, so states with several good options are valued a little higher.

  5. The soft Bellman target and loss

    y=r+γ V(s′),L(θ)=(Qθ(s,a)−y)2y = r + \gamma \, V(s'), \qquad L(\theta) = \big(Q_\theta(s, a) - y\big)^{2}

    The same idea as Q-learning with the hard maximum replaced by the soft value. The batch this is averaged over is mostly model data.

  6. Target network update

    θˉ←θˉ+τ (θ−θˉ)\bar{\theta} \leftarrow \bar{\theta} + \tau \, (\theta - \bar{\theta})

    The target network trails the trained one. Because V(s′)V(s') is computed from the slow copy, the target yy does not jump each time the weights change.

Symbols

fϕif_{\phi_i}
ensemble member i, a network with weights phi_i
Di,  DenvD_i,\; D_{\text{env}}
member i's bootstrap resample, and the buffer of real transitions
s,  a,  r,  s′s,\; a,\; r,\; s'
state, action, reward and next state
kk
length of a model rollout (rollout_length)
iti_t
index of the member used at rollout step t
π(a∣s)\pi(a \mid s)
the soft policy
Qθ,  QˉQ_\theta,\; \bar{Q}
the trained Q network and its slowly updated target copy
α\alpha
entropy temperature of the soft policy
V(s)V(s)
soft value of state s
γ\gamma
discount factor
yy
learning target for one transition
τ\tau
rate at which the target network follows the trained one (target_tau)

Worked by hand

Use the defaults. First count the data of one epoch and the make-up of one batch of 64. Then compute one learning target: the target network gives Qˉ(s′,⋅)=(−0.2,−0.2,−0.4)\bar{Q}(s', \cdot) = (-0.2, -0.2, -0.4), with α=0.05\alpha = 0.05, r=−0.4r = -0.4 and γ=0.9\gamma = 0.9.

real: 60 steps,model: 200×3=600 transitions\text{real: } 60 \text{ steps}, \qquad \text{model: } 200 \times 3 = 600 \text{ transitions}
nreal=round⁡(0.1×64)=6,nmodel=64−6=58n_{\text{real}} = \operatorname{round}(0.1 \times 64) = 6, \qquad n_{\text{model}} = 64 - 6 = 58
V(s′)=−0.2+0.05×ln⁡ ⁣(1+1+e−4)=−0.2+0.05×0.7023=−0.1649V(s') = -0.2 + 0.05 \times \ln\!\big(1 + 1 + e^{-4}\big) = -0.2 + 0.05 \times 0.7023 = -0.1649
y=−0.4+0.9×(−0.1649)=−0.5484y = -0.4 + 0.9 \times (-0.1649) = -0.5484

Each epoch adds ten times more imagined transitions than real ones. The soft value, −0.165-0.165, sits a little above the best Q value of −0.2-0.2 because two actions are equally good. A hard maximum would give −0.2-0.2.

Visual example

Loading the example.

Try this

  • Drag the rollout length k from 3 to 15 and watch the imagined rollouts leave the real line.
  • Raise the real steps collected to 180 and check whether the model has learned the wall at 2 yet.
  • Switch the policy to step toward the origin, where the data is dense and the model stays close.
  • Click the ensemble box to read how far the three networks disagree at the start state.

Code sample

from impl import MBPOAgent, ReachEnv
from config import MBPOConfig

env = ReachEnv(seed=0)
agent = MBPOAgent(MBPOConfig(), env.obs_dim, env.n_actions)
print(agent.evaluate(ReachEnv(seed=1), n_episodes=10))    # untrained: somewhere from -6 to -18
history = agent.train(env, n_epochs=6)                    # 360 real steps
print(agent.evaluate(ReachEnv(seed=1), n_episodes=10))    # trained: about -1.6, the best possible
Read the implementation (247 lines)
"""MBPO: a learned dynamics ensemble, short model rollouts branched from real states, and a soft policy trained on them.

NumPy only, manual backpropagation. The policy optimizer is soft Q-learning over discrete actions, the discrete
counterpart of the Soft Actor-Critic of the paper. `ReachEnv` is a small environment so the folder runs on its own.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import MBPOConfig
except ImportError:  # run from the template's own folder
    from config import MBPOConfig


class ReachEnv:
    """Move a point on the line to the origin.

    Observation: the position x, shape (1,), kept in [-2, 2]. Actions: 0 = step left, 1 = stay, 2 = step right;
    a step moves 0.2 plus a little noise. Reward: -|x| of the position reached. An episode starts at a random
    position in [-1.5, 1.5] and lasts `episode_length` steps (a time limit, not a terminal state).
    """

    obs_dim, n_actions = 1, 3

    def __init__(self, seed: int = 0, episode_length: int = 15, noise_std: float = 0.01) -> None:
        self.episode_length, self.noise_std = episode_length, noise_std
        self.rng = np.random.default_rng(seed)
        self.x, self.t = 0.0, 0

    def reset(self) -> np.ndarray:
        self.x, self.t = float(self.rng.uniform(-1.5, 1.5)), 0
        return np.array([self.x])

    def step(self, action: int) -> tuple[np.ndarray, float, bool]:
        """Returns (obs (1,), reward, time_is_up)."""
        move = 0.2 * (int(action) - 1) + self.noise_std * self.rng.standard_normal()
        self.x = float(np.clip(self.x + move, -2.0, 2.0))
        self.t += 1
        return np.array([self.x]), -abs(self.x), self.t >= self.episode_length


class TinyMLP:
    """Two tanh hidden layers and a linear output, with backpropagation and a built-in Adam step."""

    def __init__(self, n_in: int, n_hidden: int, n_out: int, lr: float, rng: np.random.Generator) -> None:
        self.params = []
        for a, b in ((n_in, n_hidden), (n_hidden, n_hidden), (n_hidden, n_out)):
            self.params += [rng.normal(0.0, 1.0 / np.sqrt(a), size=(a, b)), np.zeros(b)]
        self.lr = lr
        self._m = [np.zeros_like(p) for p in self.params]
        self._v = [np.zeros_like(p) for p in self.params]
        self._t = 0
        self._cache = None

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (batch, n_in) -> (batch, n_out)."""
        w1, b1, w2, b2, w3, b3 = self.params
        h1 = np.tanh(x @ w1 + b1)
        h2 = np.tanh(h1 @ w2 + b2)
        self._cache = (x, h1, h2)
        return h2 @ w3 + b3

    def gradients(self, grad_out: np.ndarray) -> list[np.ndarray]:
        """Gradients of the loss for every parameter, given dLoss/dOutput (batch, n_out) of the last forward."""
        x, h1, h2 = self._cache
        d2 = (grad_out @ self.params[4].T) * (1.0 - h2**2)
        d1 = (d2 @ self.params[2].T) * (1.0 - h1**2)
        return [x.T @ d1, d1.sum(axis=0), h1.T @ d2, d2.sum(axis=0), h2.T @ grad_out, grad_out.sum(axis=0)]

    def step(self, grads: list[np.ndarray]) -> None:
        """One Adam update."""
        self._t += 1
        for p, g, m, v in zip(self.params, grads, self._m, self._v):
            m *= 0.9
            m += 0.1 * g
            v *= 0.999
            v += 0.001 * g * g
            p -= self.lr * (m / (1 - 0.9**self._t)) / (np.sqrt(v / (1 - 0.999**self._t)) + 1e-8)


class DynamicsEnsemble:
    """Ensemble of networks predicting (next_obs - obs, reward) from (obs, one-hot action)."""

    def __init__(self, config: MBPOConfig, obs_dim: int, n_actions: int, rng: np.random.Generator) -> None:
        self.config, self.obs_dim, self.n_actions, self.rng = config, obs_dim, n_actions, rng
        self.members = [TinyMLP(obs_dim + n_actions, config.hidden_size, obs_dim + 1, config.model_lr, rng)
                        for _ in range(config.ensemble_size)]
        self.out_mean, self.out_std = np.zeros(obs_dim + 1), np.ones(obs_dim + 1)

    def _inputs(self, obs: np.ndarray, actions: np.ndarray) -> np.ndarray:
        onehot = np.zeros((len(obs), self.n_actions))
        onehot[np.arange(len(obs)), np.asarray(actions, dtype=int)] = 1.0
        return np.concatenate([obs, onehot], axis=1)

    def train(self, obs, actions, rewards, next_obs, n_steps: int | None = None) -> float:
        """Fit every member on its own bootstrap resample. Arrays have leading size N. Returns the final mean loss."""
        x = self._inputs(obs, actions)
        y = np.concatenate([next_obs - obs, np.asarray(rewards, dtype=float)[:, None]], axis=1)
        self.out_mean, self.out_std = y.mean(axis=0), y.std(axis=0) + 1e-6
        y = (y - self.out_mean) / self.out_std
        n, batch, last = len(x), min(self.config.batch_size, len(x)), []
        for net in self.members:
            boot = self.rng.integers(0, n, size=n)
            for _ in range(n_steps or self.config.model_train_steps):
                idx = boot[self.rng.integers(0, n, size=batch)]
                err = net.forward(x[idx]) - y[idx]
                net.step(net.gradients(2.0 * err / err.size))
            last.append(float((err**2).mean()))
        return float(np.mean(last))

    def predict(self, obs: np.ndarray, actions: np.ndarray, member: int | None = None):
        """Predict (next_obs (N, obs_dim), rewards (N,)) with one member, or the ensemble mean when member is None."""
        x = self._inputs(obs, actions)
        nets = self.members if member is None else [self.members[member]]
        out = np.mean([net.forward(x) for net in nets], axis=0) * self.out_std + self.out_mean
        return obs + out[:, : self.obs_dim], out[:, self.obs_dim]


class _Buffer:
    """Ring buffer of (obs, action, reward, next_obs)."""

    def __init__(self, capacity: int, obs_dim: int) -> None:
        self.obs, self.next_obs = np.zeros((capacity, obs_dim)), np.zeros((capacity, obs_dim))
        self.actions, self.rewards = np.zeros(capacity, dtype=int), np.zeros(capacity)
        self.capacity, self.size, self.pos = capacity, 0, 0

    def add_batch(self, obs, actions, rewards, next_obs) -> None:
        for o, a, r, o2 in zip(obs, actions, rewards, next_obs):
            self.obs[self.pos], self.actions[self.pos], self.rewards[self.pos], self.next_obs[self.pos] = o, a, r, o2
            self.pos = (self.pos + 1) % self.capacity
            self.size = min(self.size + 1, self.capacity)

    def sample(self, n: int, rng: np.random.Generator):
        idx = rng.integers(0, self.size, size=n)
        return self.obs[idx], self.actions[idx], self.rewards[idx], self.next_obs[idx]


class MBPOAgent:
    """MBPO with a soft Q-learning policy for discrete actions."""

    def __init__(self, config: MBPOConfig | None, obs_dim: int, n_actions: int) -> None:
        self.config = c = config or MBPOConfig()
        self.obs_dim, self.n_actions = obs_dim, n_actions
        self.rng = np.random.default_rng(c.seed)
        self.model = DynamicsEnsemble(c, obs_dim, n_actions, self.rng)
        self.q = TinyMLP(obs_dim, c.hidden_size, n_actions, c.q_lr, self.rng)
        self.q_target = TinyMLP(obs_dim, c.hidden_size, n_actions, c.q_lr, self.rng)
        for p, tp in zip(self.q.params, self.q_target.params):
            tp[...] = p
        self.real_buffer = _Buffer(100000, obs_dim)
        self.model_buffer = _Buffer(c.model_buffer_size, obs_dim)
        self._obs: np.ndarray | None = None  # where the real environment currently is

    def policy(self, obs: np.ndarray) -> np.ndarray:
        """Action probabilities softmax(Q(obs) / alpha). obs: (N, obs_dim) -> (N, n_actions)."""
        z = self.q.forward(np.asarray(obs, dtype=float)) / self.config.alpha
        z = z - z.max(axis=1, keepdims=True)
        p = np.exp(z)
        return p / p.sum(axis=1, keepdims=True)

    def act(self, obs: np.ndarray, greedy: bool = False) -> np.ndarray:
        """One action per row of obs (N, obs_dim): sampled from the soft policy, or the argmax when greedy."""
        p = self.policy(obs)
        if greedy:
            return p.argmax(axis=1)
        u = self.rng.random((len(p), 1))
        return np.minimum((p.cumsum(axis=1) < u).sum(axis=1), self.n_actions - 1)

    def collect(self, env, n_steps: int) -> None:
        """Take `n_steps` real steps with the current soft policy and store them in the real buffer."""
        for _ in range(n_steps):
            if self._obs is None:
                self._obs = env.reset()
            action = int(self.act(self._obs[None])[0])
            next_obs, reward, done = env.step(action)
            self.real_buffer.add_batch([self._obs], [action], [reward], [next_obs])
            self._obs = None if done else next_obs

    def train_model(self) -> float:
        """Fit the dynamics ensemble to the real buffer. Returns the final normalized squared error."""
        b = self.real_buffer
        return self.model.train(b.obs[: b.size], b.actions[: b.size], b.rewards[: b.size], b.next_obs[: b.size])

    def rollout_model(self) -> int:
        """Branch `rollout_length`-step model rollouts from real states into the model buffer. Returns how many
        transitions were added (rollouts_per_epoch * rollout_length)."""
        c = self.config
        if c.rollout_length == 0 or c.rollouts_per_epoch == 0:
            return 0
        obs = self.real_buffer.sample(c.rollouts_per_epoch, self.rng)[0]
        for _ in range(c.rollout_length):
            actions = self.act(obs)
            next_obs, rewards = self.model.predict(obs, actions, member=int(self.rng.integers(c.ensemble_size)))
            self.model_buffer.add_batch(obs, actions, rewards, next_obs)
            obs = next_obs
        return c.rollouts_per_epoch * c.rollout_length

    def _soft_value(self, obs: np.ndarray) -> np.ndarray:
        """V(s) = alpha * log sum_a exp(Q_target(s, a) / alpha), shape (N,)."""
        z = self.q_target.forward(obs) / self.config.alpha
        m = z.max(axis=1)
        return self.config.alpha * (m + np.log(np.exp(z - m[:, None]).sum(axis=1)))

    def update_policy(self, n_updates: int | None = None) -> float:
        """Soft Q-learning steps on mixed real and model batches. Returns the mean squared TD error."""
        c = self.config
        n_real = c.batch_size if self.model_buffer.size == 0 else max(1, int(round(c.real_ratio * c.batch_size)))
        losses = []
        for _ in range(n_updates or c.policy_updates_per_epoch):
            parts = [self.real_buffer.sample(n_real, self.rng)]
            if n_real < c.batch_size:
                parts.append(self.model_buffer.sample(c.batch_size - n_real, self.rng))
            obs, actions, rewards, next_obs = (np.concatenate(x) for x in zip(*parts))
            target = rewards + c.gamma * self._soft_value(next_obs)
            q = self.q.forward(obs)
            rows = np.arange(len(obs))
            td = q[rows, actions] - target
            grad = np.zeros_like(q)
            grad[rows, actions] = 2.0 * td / len(obs)
            self.q.step(self.q.gradients(grad))
            for p, tp in zip(self.q.params, self.q_target.params):
                tp += c.target_tau * (p - tp)
            losses.append(float((td**2).mean()))
        return float(np.mean(losses))

    def train(self, env, n_epochs: int) -> list[dict]:
        """Run the MBPO loop. Returns one dict per epoch: model_loss, td_loss, real_steps, model_transitions."""
        history = []
        for _ in range(n_epochs):
            self.collect(env, self.config.steps_per_epoch)
            model_loss = self.train_model()
            self.rollout_model()
            td_loss = self.update_policy()
            history.append({"model_loss": model_loss, "td_loss": td_loss, "real_steps": self.real_buffer.size,
                            "model_transitions": self.model_buffer.size})
        return history

    def evaluate(self, env, n_episodes: int = 10) -> float:
        """Mean undiscounted return of the greedy policy over `n_episodes` episodes."""
        total = 0.0
        for _ in range(n_episodes):
            obs, done = env.reset(), False
            while not done:
                obs, reward, done = env.step(int(self.act(obs[None], greedy=True)[0]))
                total += reward
        return total / n_episodes
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Create env = ReachEnv(seed=0) and agent = MBPOAgent(MBPOConfig(), env.obs_dim, env.n_actions). Record agent.evaluate(ReachEnv(seed=1)), call agent.train(env, n_epochs=6), and evaluate again. Repeat with rollout_length=0, which trains on real data only, and with rollout_length=15. Compare the three final scores and the td_loss in each history. On this small task the gaps are small. Explain what about ReachEnv makes its dynamics easy to model.

Check on learning

  1. Why does MBPO start its imagined rollouts from states in the real buffer instead of from the start state of an episode?
    A way to think about it

    To reach a late state from the start, the model would need many accurate steps in a row. Compare that with reaching a state three steps after one that really occurred.

  2. Suppose each model step has a small error. Describe how the error in the predicted state grows over a rollout, and why the growth is worse than adding up the single-step errors.
    A way to think about it

    The second step is predicted from an input the model was never trained on. Ask how reliable a network is on inputs outside its training data.

  3. Each rollout step uses a randomly chosen ensemble member. What does that do for the policy that using the average of all members would not?
    A way to think about it

    Where the members disagree, random choice produces inconsistent outcomes. Consider whether a policy can rely on a reward that only one member predicts.

  4. If the model were perfect, would there be any reason to keep real_ratio above zero? And when the model is poor, what does the real share protect?
    A way to think about it

    Think about which transitions carry true rewards and true next states, and what anchors the Q values when imagined ones are biased.

  5. As the policy improves, it visits states the model was not trained on. How does the epoch loop deal with this, and what would break if the model were trained only once?
    A way to think about it

    Follow the order of the four stages. The model is refit on a buffer that keeps growing with data from the current policy.