Sign in

PETS

Probabilistic Ensembles with Trajectory Sampling

Learn an ensemble of networks that each predict a Gaussian over the next state, then choose every action by planning through the ensemble with the cross-entropy method.

Overview

A model learned from little data is wrong in two different ways. Some of what it cannot predict is real randomness in the world. The rest is ignorance: it has not seen enough. PETS keeps the two apart. Each network predicts a spread as well as a mean, which captures the randomness. Several networks trained on different resamples of the data disagree where data is thin, which exposes the ignorance. To act, the agent imagines many candidate action sequences, runs each through the ensemble several times, and prefers sequences that score well on average. It then takes only the first action and plans again. This template is a small NumPy version for states of a few dimensions.

A short history

Kurtland Chua, Roberto Calandra, Rowan McAllister and Sergey Levine at UC Berkeley published PETS in 2018 in the paper Deep Reinforcement Learning in a Handful of Trials using Probabilistic Dynamics Models. Earlier model-based methods with neural networks fell short of model-free results because the planner exploited model errors. PETS separated two kinds of uncertainty, noise in the world and ignorance of the model, using an ensemble of probabilistic networks, and reached similar performance on several control benchmarks with far less data.

How it works

  1. PETSAgent.run_episode with random_actions=True gathers the first transitions. add stores each one as an input (state and action) and a target (the change in state).
  2. train_model fits ProbabilisticEnsemble. Every member outputs a mean and a log variance and is trained with the Gaussian negative log-likelihood on its own bootstrap resample.
  3. To choose an action, plan samples population action sequences of length horizon from a Gaussian.
  4. evaluate_sequences copies each sequence into n_particles particles, steps every particle through the ensemble by sampling from a member's predicted Gaussian, and sums the known reward along the way.
  5. The score of a sequence is the mean return of its particles. The Gaussian is refit to the n_elites best sequences, and this is repeated cem_iterations times.
  6. act returns the first action of the final plan. At the next step the plan is shifted by one and used to start the new search.
  7. The new real transitions are added to the data, and the model is trained again before the next episode.

Watch out for

  • Planning is costly: with the defaults one decision simulates 3 rounds of 100 sequences, 5 particles and 10 steps, which is 15000 imagined transitions.
  • The reward function must be given. If you can only observe rewards, you have to learn a reward model too, and its errors will be planned against like any others.
  • The predicted variance can collapse or blow up during training. This template bounds the log variance with fixed limits, where the original method learns the limits.
  • A horizon that is too short makes the agent ignore consequences beyond it, such as arriving at the target too fast to stop. A horizon that is too long compounds model error.
  • If the first random episodes never visit an important region, every member is equally ignorant there and their agreement means nothing.

Use cases

When to use it

Use it when real interaction is expensive, the reward function is known, the state is low-dimensional and you can afford planning at every step. When a fast reactive policy is needed at run time, MBPO fits better.

In industry

Robotics
Learning reaching or pushing with a robot arm from a small number of trials, replanning every step with the learned model.
Process control
Model predictive control of a simulated plant where the reward is known and the dynamics are learned from limited operating data.
Research
A standard model-based baseline for sample efficiency on continuous control tasks.

Choosing it: what must hold

  • A reward function you can compute for imagined states, since the planner scores trajectories with it.
  • Compute at decision time: every action needs many model rollouts through the cross-entropy method.
  • Low-dimensional state vectors and short planning horizons, where learned models stay accurate.

When to choose something else

IfUse instead
Actions must be chosen very quickly at run timeMBPO, which trains a fast policy from the model
Environment steps are cheapSAC or TD3 without a model
Actions are discrete and a simulator existsMonte Carlo tree search from the shared planning lesson, or AlphaZero

Math foundations

  1. One probabilistic member

    pθb(Δs∣s,a)=N ⁣(μθb(s,a),  diag⁡ σθb2(s,a)),Δs=s′−sp_{\theta_b}(\Delta s \mid s, a) = \mathcal{N}\!\big(\mu_{\theta_b}(s, a),\; \operatorname{diag}\,\sigma^{2}_{\theta_b}(s, a)\big), \qquad \Delta s = s' - s

    Each network predicts a distribution over the change in state, not a single guess. The mean is its best estimate. The variance is how much it expects the outcome to scatter around that estimate.

  2. Gaussian negative log-likelihood

    L(θb)=12∑d[(μd−yd)2σd2+log⁡σd2]L(\theta_b) = \frac{1}{2} \sum_{d} \left[ \frac{\big(\mu_d - y_d\big)^{2}}{\sigma_d^{2}} + \log \sigma_d^{2} \right]

    The first term punishes errors, but less where the network admitted uncertainty. The second term punishes claiming uncertainty. The balance is best when the predicted variance equals the actual squared error. A constant is left out, and the template averages this over the batch and dimensions.

  3. Keeping the log variance in bounds

    ℓ′=ℓmax⁡−softplus⁡(ℓmax⁡−ℓ),log⁡σ2=ℓmin⁡+softplus⁡(ℓ′−ℓmin⁡)\ell' = \ell_{\max} - \operatorname{softplus}(\ell_{\max} - \ell), \qquad \log \sigma^{2} = \ell_{\min} + \operatorname{softplus}(\ell' - \ell_{\min})

    A smooth clamp on the raw output ℓ\ell. It stops the variance from running off to zero or infinity, which would make the loss unstable, while keeping the gradient alive near the limits.

  4. Trajectory sampling

    st+1=st+μθb(st,at)+σθb(st,at)⊙ξt,ξt∼N(0,I)s_{t+1} = s_t + \mu_{\theta_{b}}(s_t, a_t) + \sigma_{\theta_{b}}(s_t, a_t) \odot \xi_t, \qquad \xi_t \sim \mathcal{N}(0, I)

    A particle moves by sampling from one member's Gaussian. With ts_inf the particle keeps the same member bb for the whole rollout, so it lives in one consistent version of the world. With ts1 it draws a new member every step.

  5. Score of an action sequence

    J(a0:H−1)=1P∑p=1P∑t=0H−1r(st(p),at,st+1(p))J(a_{0:H-1}) = \frac{1}{P} \sum_{p=1}^{P} \sum_{t=0}^{H-1} r\big(s_t^{(p)}, a_t, s_{t+1}^{(p)}\big)

    The average return over the particles. A sequence that only works under one member's beliefs, or only when the noise is kind, scores worse than one that works across all of them.

  6. Cross-entropy method refit

    μ←mean⁡(elites),σ←std⁡(elites)\mu \leftarrow \operatorname{mean}(\text{elites}), \qquad \sigma \leftarrow \operatorname{std}(\text{elites})

    After scoring, the sampling distribution over action sequences is moved onto the best few. Repeating this narrows the search around good plans without needing any gradient of the model.

Symbols

s,  a,  s′s,\; a,\; s'
state, action and next state
Δs\Delta s
the change in state that the model predicts
θb\theta_b
weights of ensemble member b
μθb,  σθb2\mu_{\theta_b},\; \sigma^{2}_{\theta_b}
predicted mean and variance of member b
yd,  μd,  σd2y_d,\; \mu_d,\; \sigma_d^{2}
target, predicted mean and predicted variance in output dimension d
ℓ,  ℓmin⁡,  ℓmax⁡\ell,\; \ell_{\min},\; \ell_{\max}
raw log variance output and its lower and upper bounds
ξt\xi_t
a vector of standard normal draws
HH
planning horizon in steps
PP
particles per action sequence (n_particles)
r(s,a,s′)r(s, a, s')
the known reward function
JJ
estimated return of an action sequence
μ,  σ\mu,\; \sigma
in the last formula: mean and spread of the sampling distribution over action sequences

Worked by hand

A member predicts a mean that misses the target by 0.5 in one dimension. Compare the loss 12[(μ−y)2/σ2+ln⁡σ2]\tfrac{1}{2}\big[(\mu - y)^{2} / \sigma^{2} + \ln \sigma^{2}\big] for three predicted variances: 1, 0.25 and 0.01.

σ2=1:12[0.251+ln⁡1]=0.125\sigma^{2} = 1: \quad \tfrac{1}{2}\left[\frac{0.25}{1} + \ln 1\right] = 0.125
σ2=0.25:12[0.250.25+ln⁡0.25]=12 [1−1.386]=−0.193\sigma^{2} = 0.25: \quad \tfrac{1}{2}\left[\frac{0.25}{0.25} + \ln 0.25\right] = \tfrac{1}{2}\,[1 - 1.386] = -0.193
σ2=0.01:12[0.250.01+ln⁡0.01]=12 [25−4.605]=10.197\sigma^{2} = 0.01: \quad \tfrac{1}{2}\left[\frac{0.25}{0.01} + \ln 0.01\right] = \tfrac{1}{2}\,[25 - 4.605] = 10.197

The loss is lowest when the predicted variance, 0.25, equals the squared error, 0.520.5^{2}. Claiming too much certainty is punished far harder than claiming too little, which pushes the model toward honest error bars.

Visual example

Loading the example.

Try this

  • Raise the real transitions from 10 to 120 and watch the fan of particles close up.
  • Go back to 10 and switch to ts1: mixing members at every step hides how much they disagree.
  • Press Take the first action for real a few times and see the plan made again from each new state.
  • Set the CEM rounds to 1 and compare the plan's expected return with 5 rounds.

Code sample

from impl import PETSAgent, PointMassEnv
from config import PETSConfig

env = PointMassEnv(seed=0)
agent = PETSAgent(PETSConfig(), env.state_dim, env.action_dim, env.reward_fn)
print(agent.run_episode(env, random_actions=True))    # gather data with random actions (poor return)
agent.train_model()                                   # fit the ensemble to everything seen so far
print(agent.run_episode(env))                         # plan with the model (return close to 0)
Read the implementation (247 lines)
"""PETS: an ensemble of probabilistic dynamics networks, used for planning with CEM and trajectory sampling.

NumPy only, manual backpropagation. The ensemble is vectorized: every weight carries a leading axis of size
`ensemble_size`, so all members run in one batched matrix product.
"""
from __future__ import annotations

from typing import Callable

import numpy as np

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


class PointMassEnv:
    """Noisy double integrator. State (position, velocity), action = force in [-1, 1].

    velocity += dt * force + noise; position += dt * velocity. The reward of a step is
    -(position^2 + 0.1 * velocity^2) of the state reached. Episodes last `episode_length` steps and start at a
    random position in [-1, 1] with zero velocity.
    """

    state_dim, action_dim = 2, 1

    def __init__(self, seed: int = 0, dt: float = 0.2, noise_std: float = 0.01, episode_length: int = 30) -> None:
        self.dt, self.noise_std, self.episode_length = dt, noise_std, episode_length
        self.rng = np.random.default_rng(seed)
        self.state = np.zeros(2)
        self.t = 0

    def reset(self, position: float | None = None) -> np.ndarray:
        """Start an episode at `position` (random when None). Returns the state, shape (2,)."""
        self.state = np.array([self.rng.uniform(-1, 1) if position is None else position, 0.0])
        self.t = 0
        return self.state.copy()

    def step(self, action) -> tuple[np.ndarray, float, bool]:
        """Returns (next_state (2,), reward, done)."""
        force = float(np.clip(np.asarray(action).ravel()[0], -1.0, 1.0))
        vel = self.state[1] + self.dt * force + self.noise_std * self.rng.standard_normal()
        pos = self.state[0] + self.dt * vel
        self.state = np.array([pos, vel])
        self.t += 1
        return self.state.copy(), float(self.reward_fn(None, None, self.state[None])[0]), self.t >= self.episode_length

    @staticmethod
    def reward_fn(states, actions, next_states: np.ndarray) -> np.ndarray:
        """Batched reward: next_states (N, 2) -> (N,)."""
        return -(next_states[:, 0] ** 2 + 0.1 * next_states[:, 1] ** 2)


def _softplus(x: np.ndarray) -> np.ndarray:
    return np.logaddexp(0.0, x)


def _sigmoid(x: np.ndarray) -> np.ndarray:
    return 0.5 * (1.0 + np.tanh(0.5 * x))


class ProbabilisticEnsemble:
    """Ensemble of networks mapping an input (state, action) to a Gaussian over a target (the state change)."""

    def __init__(self, config: PETSConfig | None, input_dim: int, output_dim: int) -> None:
        self.config = config or PETSConfig()
        self.input_dim, self.output_dim = input_dim, output_dim
        e, h = self.config.ensemble_size, self.config.hidden_size
        self.rng = np.random.default_rng(self.config.seed)
        sizes = [(input_dim, h), (h, h), (h, 2 * output_dim)]
        self.params = []  # W1, b1, W2, b2, W3, b3 with shapes (E, n_in, n_out) and (E, 1, n_out)
        for n_in, n_out in sizes:
            self.params.append(self.rng.normal(0.0, 1.0 / np.sqrt(n_in), size=(e, n_in, n_out)))
            self.params.append(np.zeros((e, 1, n_out)))
        self._adam_m = [np.zeros_like(p) for p in self.params]
        self._adam_v = [np.zeros_like(p) for p in self.params]
        self._adam_t = 0
        self.in_mean, self.in_std = np.zeros(input_dim), np.ones(input_dim)
        self.out_mean, self.out_std = np.zeros(output_dim), np.ones(output_dim)

    def _forward(self, x: np.ndarray):
        """x: normalized inputs (E, B, input_dim). Returns (mean, logvar, cache), mean and logvar (E, B, output_dim)."""
        w1, b1, w2, b2, w3, b3 = self.params
        h1 = np.tanh(x @ w1 + b1)
        h2 = np.tanh(h1 @ w2 + b2)
        out = h2 @ w3 + b3
        mean, raw = out[..., : self.output_dim], out[..., self.output_dim :]
        hi, lo = self.config.max_logvar, self.config.min_logvar
        upper = hi - _softplus(hi - raw)  # smooth clamp from above
        logvar = lo + _softplus(upper - lo)  # smooth clamp from below (so the top is lo + softplus(hi - lo))
        return mean, logvar, (x, h1, h2, raw, upper)

    def loss_and_grads(self, x: np.ndarray, y: np.ndarray) -> tuple[float, list[np.ndarray]]:
        """Gaussian negative log-likelihood, summed over members and averaged over batch and output dimensions.

        x: normalized inputs (E, B, input_dim). y: normalized targets (E, B, output_dim).
        loss = sum_e mean_{b,d} 0.5 * ((mean - y)^2 * exp(-logvar) + logvar). Returns (loss, gradients like params).
        """
        mean, logvar, (x, h1, h2, raw, upper) = self._forward(x)
        inv_var = np.exp(-logvar)
        err = mean - y
        n = y.shape[1] * y.shape[2]
        loss = float((0.5 * (err**2 * inv_var + logvar)).sum() / n)
        d_mean = err * inv_var / n
        d_logvar = 0.5 * (1.0 - err**2 * inv_var) / n
        hi, lo = self.config.max_logvar, self.config.min_logvar
        d_raw = d_logvar * _sigmoid(upper - lo) * _sigmoid(hi - raw)
        d_out = np.concatenate([d_mean, d_raw], axis=-1)
        w1, b1, w2, b2, w3, b3 = self.params
        g_w3 = np.swapaxes(h2, 1, 2) @ d_out
        d_h2 = (d_out @ np.swapaxes(w3, 1, 2)) * (1.0 - h2**2)
        g_w2 = np.swapaxes(h1, 1, 2) @ d_h2
        d_h1 = (d_h2 @ np.swapaxes(w2, 1, 2)) * (1.0 - h1**2)
        g_w1 = np.swapaxes(x, 1, 2) @ d_h1
        grads = [g_w1, d_h1.sum(axis=1, keepdims=True), g_w2, d_h2.sum(axis=1, keepdims=True),
                 g_w3, d_out.sum(axis=1, keepdims=True)]
        return loss, grads

    def _adam_step(self, grads: list[np.ndarray]) -> None:
        self._adam_t += 1
        lr, b1, b2 = self.config.learning_rate, 0.9, 0.999
        for p, g, m, v in zip(self.params, grads, self._adam_m, self._adam_v):
            m *= b1
            m += (1 - b1) * g
            v *= b2
            v += (1 - b2) * g * g
            p -= lr * (m / (1 - b1**self._adam_t)) / (np.sqrt(v / (1 - b2**self._adam_t)) + 1e-8)

    def train(self, inputs: np.ndarray, targets: np.ndarray, n_steps: int | None = None) -> list[float]:
        """Fit the ensemble. inputs (N, input_dim), targets (N, output_dim). Returns the loss after each step.

        Inputs and targets are normalized with the statistics of this data. Each member sees its own bootstrap
        resample (N draws with replacement), which is what makes the members disagree where data is thin.
        """
        inputs, targets = np.asarray(inputs, dtype=float), np.asarray(targets, dtype=float)
        self.in_mean, self.in_std = inputs.mean(axis=0), inputs.std(axis=0) + 1e-6
        self.out_mean, self.out_std = targets.mean(axis=0), targets.std(axis=0) + 1e-6
        x = (inputs - self.in_mean) / self.in_std
        y = (targets - self.out_mean) / self.out_std
        e, n = self.config.ensemble_size, len(x)
        bootstrap = self.rng.integers(0, n, size=(e, n))
        batch = min(self.config.batch_size, n)
        losses = []
        for _ in range(n_steps or self.config.train_steps):
            pick = np.take_along_axis(bootstrap, self.rng.integers(0, n, size=(e, batch)), axis=1)
            loss, grads = self.loss_and_grads(x[pick], y[pick])
            self._adam_step(grads)
            losses.append(loss)
        return losses

    def predict(self, inputs: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Every member's Gaussian for every input, in the units of the training targets.

        inputs: (N, input_dim). Returns (mean, variance), each of shape (E, N, output_dim).
        """
        x = (np.asarray(inputs, dtype=float) - self.in_mean) / self.in_std
        mean, logvar, _ = self._forward(np.broadcast_to(x, (self.config.ensemble_size, *x.shape)))
        return mean * self.out_std + self.out_mean, np.exp(logvar) * self.out_std**2


class PETSAgent:
    """Collects transitions, fits the ensemble and picks actions by CEM planning through it."""

    def __init__(self, config: PETSConfig | None, state_dim: int, action_dim: int, reward_fn: Callable) -> None:
        """reward_fn(states (N, S), actions (N, A), next_states (N, S)) -> rewards (N,). It is given, not learned."""
        self.config = config or PETSConfig()
        self.state_dim, self.action_dim, self.reward_fn = state_dim, action_dim, reward_fn
        self.model = ProbabilisticEnsemble(self.config, state_dim + action_dim, state_dim)
        self.rng = np.random.default_rng(self.config.seed + 1)
        self.inputs: list[np.ndarray] = []
        self.targets: list[np.ndarray] = []
        self._plan: np.ndarray | None = None

    def add(self, state: np.ndarray, action: np.ndarray, next_state: np.ndarray) -> None:
        """Store one real transition. The model learns the change next_state - state."""
        self.inputs.append(np.concatenate([state, np.atleast_1d(action)]))
        self.targets.append(np.asarray(next_state, dtype=float) - np.asarray(state, dtype=float))

    def train_model(self, n_steps: int | None = None) -> list[float]:
        """Fit the ensemble to all stored transitions. Returns the training losses."""
        return self.model.train(np.array(self.inputs), np.array(self.targets), n_steps)

    def evaluate_sequences(self, state: np.ndarray, action_seqs: np.ndarray) -> np.ndarray:
        """Expected return of each action sequence under the ensemble, by trajectory sampling.

        state: (state_dim,). action_seqs: (N, horizon, action_dim). Returns (N,): the mean over `n_particles`
        sampled trajectories of the summed reward.
        """
        c = self.config
        n, horizon, _ = action_seqs.shape
        rows = n * c.n_particles
        states = np.repeat(np.asarray(state, dtype=float)[None], rows, axis=0)
        member = self.rng.integers(0, c.ensemble_size, size=rows)  # ts_inf: fixed for the whole rollout
        returns = np.zeros(rows)
        row_ids = np.arange(rows)
        for t in range(horizon):
            actions = np.repeat(action_seqs[:, t], c.n_particles, axis=0)
            if c.propagation == "ts1":
                member = self.rng.integers(0, c.ensemble_size, size=rows)
            mean, var = self.model.predict(np.concatenate([states, actions], axis=1))
            delta = mean[member, row_ids] + np.sqrt(var[member, row_ids]) * self.rng.standard_normal((rows, self.state_dim))
            next_states = states + delta
            returns += self.reward_fn(states, actions, next_states)
            states = next_states
        return returns.reshape(n, c.n_particles).mean(axis=1)

    def plan(self, state: np.ndarray) -> np.ndarray:
        """CEM over action sequences from `state`. Returns the plan, shape (horizon, action_dim)."""
        c = self.config
        shape = (c.horizon, self.action_dim)
        if self._plan is None:
            mean = np.full(shape, 0.5 * (c.action_low + c.action_high))
        else:  # warm start: last plan shifted by one step
            mean = np.concatenate([self._plan[1:], self._plan[-1:]], axis=0)
        std = np.full(shape, 0.5 * (c.action_high - c.action_low))
        for _ in range(c.cem_iterations):
            seqs = np.clip(mean + std * self.rng.standard_normal((c.population, *shape)), c.action_low, c.action_high)
            scores = self.evaluate_sequences(state, seqs)
            elites = seqs[np.argsort(scores)[-c.n_elites:]]
            mean, std = elites.mean(axis=0), elites.std(axis=0) + 1e-6
        self._plan = mean
        return mean

    def act(self, state: np.ndarray) -> np.ndarray:
        """Action for `state` by replanning: the first action of a fresh CEM plan, shape (action_dim,)."""
        return self.plan(state)[0].copy()

    def run_episode(self, env, random_actions: bool = False, position: float | None = None) -> float:
        """Run one episode, store its transitions and return its total reward.

        random_actions: act uniformly at random (to gather the first data) instead of planning.
        position: optional fixed start position passed to `env.reset`.
        """
        c = self.config
        state, total, done = env.reset(position), 0.0, False
        self._plan = None
        while not done:
            if random_actions:
                action = self.rng.uniform(c.action_low, c.action_high, size=self.action_dim)
            else:
                action = self.act(state)
            next_state, reward, done = env.step(action)
            self.add(state, action, next_state)
            total += reward
            state = next_state
        return total
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Create env = PointMassEnv(seed=0) and agent = PETSAgent(PETSConfig(), env.state_dim, env.action_dim, PointMassEnv.reward_fn). Run two episodes with run_episode(env, random_actions=True), call train_model(), then run run_episode(env, position=1.0) and compare the returns. After that, call agent.model.predict on an input near the data and on one far from it, and compare how much the member means differ.

Check on learning

  1. One large network could also output a mean and a variance. What kind of uncertainty would it still miss, and why does an ensemble see it?
    A way to think about it

    A single network far from its data still gives one confident answer. Ask what several networks trained on different resamples do in a region none of them has seen.

  2. Why does the planner take only the first action of a ten-step plan and then plan again from scratch?
    A way to think about it

    Compare the state the model predicted for the next step with the state the real environment produces. Then ask what happens to a fixed plan after a few such differences.

  3. With ts_inf a particle keeps one ensemble member for the whole rollout. With ts1 it changes member at every step. Which better represents the idea that one of these models may be the true one?
    A way to think about it

    If the world follows a single set of laws, think about whether a path that switches laws at every step could ever happen.

  4. Suppose you removed the log⁡σ2\log \sigma^{2} term from the loss. What would the network learn to output for the variance?
    A way to think about it

    Look at the remaining term and ask which value of σ2\sigma^{2} makes it as small as possible, whatever the error.

  5. The agent learns the point mass from only one or two random episodes. Why would the same recipe struggle on a task where random actions never reach the interesting states?
    A way to think about it

    The model is only as good as the data under it. Think about what the planner optimizes in regions where all members are guessing.