Sign in

Planning

Shared planning utilities: tree search and predictive control

Planners that choose actions by looking ahead in a model you already have: Monte Carlo tree search for discrete actions, and random shooting, the cross-entropy method and MPC for continuous ones.

Overview

If you can ask what would happen if you did something, you can try actions in your head before committing to one. A planner does exactly that. For a handful of discrete actions it grows a tree of possible futures, spending more simulations on branches that look promising while still checking the others. For continuous actions a tree is not practical, so it samples many whole action sequences, scores each with the model, and keeps or refines the best. In both cases the plan is only as good as the model, so the usual practice is to execute one action, observe the real result, and plan again.

A short history

The methods come from two fields. Model predictive control grew out of the process industries in the 1970s, where controllers replanned over a moving horizon at every step. The cross-entropy method was developed by Reuven Rubinstein in the late 1990s. Monte Carlo tree search was named by Rémi Coulom in 2006, and the same year Levente Kocsis and Csaba Szepesvári gave it the UCT rule for balancing exploration in the tree. It transformed computer Go and became the search inside AlphaGo.

How it works

  1. MCTS.search runs n_simulations descents from the current state. Each descent follows the UCT rule down the tree until it reaches a node with an untried action.
  2. It tries one untried action there, adds the resulting state as a new node, and scores it with a random rollout of at most rollout_depth steps.
  3. The return is passed back up the path, adding each node's reward and discounting, and every node on the path counts one more visit. search returns the most visited root action.
  4. rollout_returns takes a batch of action sequences and computes the discounted return of each under a batched dynamics function and reward function.
  5. random_shooting samples population sequences uniformly within the action bounds and returns the best one.
  6. cem_plan samples sequences from a Gaussian, refits the Gaussian to the n_elites best, repeats cem_iterations times, and returns the final mean.
  7. MPCController.act plans, returns the first action, and starts the next plan from the previous one shifted by a step.

Watch out for

  • The planners trust the model completely. If it is wrong, they will find and use exactly the actions where it is too optimistic.
  • This MCTS stores one state per tree node, so the model must be deterministic. With random outcomes the same action sequence could lead to different states and the tree would be wrong.
  • A random rollout is a weak judge of a position. When good play needs many precise moves, random play rarely finds the reward and promising branches look worthless.
  • Random shooting scales badly: the number of samples needed to land near a good sequence grows quickly with the horizon and the action dimension.
  • CEM can narrow onto a mediocre plan if the elite set is small. Once the standard deviation has shrunk, it no longer samples the better region.

Use cases

When to use it

Use MCTS when actions are discrete and the model is queried one state at a time, as in board games and small decision problems. Use CEM or random shooting inside MPC when actions are continuous and the dynamics can be evaluated on a whole batch of candidates.

In industry

Board games
Go, chess and general game-playing programs use Monte Carlo tree search to decide each move from simulated continuations.
Process industries
Refineries and chemical plants use model predictive control to hold setpoints while respecting limits on temperatures, pressures and flows.
Robotics and vehicles
Sampling-based planners such as the cross-entropy method replan a short sequence of continuous controls at every time step.

Choosing it: what must hold

  • A model of the environment you can query: given a state and action, it returns the next state and reward.
  • Enough compute at decision time to run many simulated steps before each real action.
  • A horizon short enough, or a value estimate good enough, that the look-ahead is informative.

When to choose something else

IfUse instead
No model exists and one must be learned from dataPETS or MBPO
You want the search to improve itself through learningAlphaZero, or MuZero if the rules are unknown
Decisions must be instant at run timeA learned policy such as PPO or SAC

Math foundations

  1. What every planner maximizes

    J(a0,…,aH−1)=∑t=0H−1γt r(st,at,st+1),st+1=f(st,at)J(a_0, \dots, a_{H-1}) = \sum_{t=0}^{H-1} \gamma^{t} \, r(s_t, a_t, s_{t+1}), \qquad s_{t+1} = f(s_t, a_t)

    The discounted return of an action sequence when the model ff is stepped forward from the current state. rollout_returns computes this for many sequences at once.

  2. UCT selection

    a∗=arg⁡max⁡a[W(s,a)N(s,a)+cln⁡N(s)N(s,a)]a^{*} = \arg\max_{a} \left[ \frac{W(s, a)}{N(s, a)} + c \sqrt{\frac{\ln N(s)}{N(s, a)}} \right]

    The first term is the average return of the action so far. The second is a bonus that is large for actions tried rarely compared with their parent. It shrinks as an action is tried, so every action keeps being rechecked, but less and less often.

  3. Backup along the path

    G←r+γ GG \leftarrow r + \gamma \, G

    Working from the leaf to the root, each node adds the reward of the step that led to it and discounts what came after. This GG is added to the node's total WW.

  4. Random shooting

    A∗=arg⁡max⁡i=1,…,nJ(Ai),Ai∼Uniform⁡[alow,ahigh]H×dA^{*} = \arg\max_{i = 1, \dots, n} J(A_i), \qquad A_i \sim \operatorname{Uniform}\big[a_{\text{low}}, a_{\text{high}}\big]^{H \times d}

    The simplest planner: guess many sequences and keep the best. It needs no gradient and no structure, only a model that can be evaluated in batches.

  5. Cross-entropy method

    μ←1K∑i∈eliteAi,σ←1K∑i∈elite(Ai−μ)2\mu \leftarrow \frac{1}{K} \sum_{i \in \text{elite}} A_i, \qquad \sigma \leftarrow \sqrt{\frac{1}{K} \sum_{i \in \text{elite}} (A_i - \mu)^{2}}

    Guess, then learn from the guesses: sample from a Gaussian over sequences, keep the KK best, and move the Gaussian onto them. After a few rounds the samples cluster around a good plan.

  6. Receding horizon and warm start

    at=μ0,μjnext=μj+1    (j<H−1),μH−1next=μH−1a_t = \mu_0, \qquad \mu^{\text{next}}_{j} = \mu_{j+1} \;\; (j < H - 1), \qquad \mu^{\text{next}}_{H-1} = \mu_{H-1}

    MPC applies only the first planned action. The rest of the plan, shifted one step earlier, becomes the starting mean of the next search, so each step refines the last plan and does not start over.

Symbols

st,  ats_t,\; a_t
state and action at step t of an imagined rollout
f,  rf,\; r
the given dynamics model and reward function
HH
planning horizon in steps
γ\gamma
discount factor
JJ
discounted return of an action sequence
N(s),  N(s,a)N(s),\; N(s, a)
visits to a tree node, and to its child for action a
W(s,a)W(s, a)
sum of the returns backed up through action a
cc
exploration constant of the UCT rule (c_uct)
GG
return being passed up the tree
AiA_i
the i-th sampled action sequence, of shape horizon by action dimension d
n,  Kn,\; K
sequences sampled per round (population) and elites kept (n_elites)
μ,  σ\mu,\; \sigma
mean and standard deviation of the CEM sampling distribution

Worked by hand

In the built-in CorridorModel the agent starts at cell 2 of 7. The left exit is 2 steps away and pays 0.3. The right exit is 4 steps away and pays 1. Use γ=0.99\gamma = 0.99. Then apply UCT at a root with 20 visits and c=1.4c = 1.4, where left has mean 0.3 over 15 visits and right has mean 0.5 over 5 visits.

J(left, left)=0+0.99×0.3=0.297J(\text{left, left}) = 0 + 0.99 \times 0.3 = 0.297
J(right×4)=0.993×1=0.970J(\text{right} \times 4) = 0.99^{3} \times 1 = 0.970
UCT(left)=0.3+1.4ln⁡2015=0.3+0.626=0.926\text{UCT}(\text{left}) = 0.3 + 1.4 \sqrt{\frac{\ln 20}{15}} = 0.3 + 0.626 = 0.926
UCT(right)=0.5+1.4ln⁡205=0.5+1.084=1.584\text{UCT}(\text{right}) = 0.5 + 1.4 \sqrt{\frac{\ln 20}{5}} = 0.5 + 1.084 = 1.584

The far exit is worth more than three times the near one, but a rollout has to make four correct moves to see it. UCT sends the next simulation right, both because its average is higher and because it has been tried less.

Visual example

Loading the example.

Try this

  • Clear the tree and press One simulation several times to see select, expand, roll out and back up one at a time.
  • Press Run and watch the visits shift from the near exit to the far one.
  • Set the longest random rollout to 0 so leaves are worth nothing until the tree itself reaches an exit.
  • Set c to 0 and run again: without the bonus the search stops rechecking the side it tried less.

Code sample

import numpy as np
from impl import MCTS, CorridorModel, MPCController, PointMassModel
from config import PlanningConfig

corridor = CorridorModel()
action = MCTS(PlanningConfig(n_simulations=300, gamma=0.95), corridor).search(corridor.start)   # 1 = right

mass = PointMassModel()
mpc = MPCController(PlanningConfig(horizon=10, population=100, n_elites=10), mass.dynamics, mass.reward)
state = np.array([1.0, 0.0])                        # position, velocity
for _ in range(30):
    state = mass.dynamics(state[None], mpc.act(state)[None])[0]
print(state)                                        # close to [0, 0]
Read the implementation (218 lines)
"""Shared planning utilities: UCT Monte Carlo tree search, random shooting, the cross-entropy method and MPC.

NumPy only. The planners work on a model that is handed to them:

- MCTS needs an object with `legal_actions(state) -> list` and `step(state, action) -> (next_state, reward, done)`.
- The shooting planners need `dynamics_fn(states (N, state_dim), actions (N, action_dim)) -> next states` and
  `reward_fn(states, actions, next_states) -> rewards (N,)`.
"""
from __future__ import annotations

import math
from typing import Callable

import numpy as np

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


class CorridorModel:
    """Deterministic corridor with cells 0..length-1; action 0 steps left, action 1 steps right.

    Reaching cell 0 ends the episode with `left_reward`, reaching the last cell ends it with `right_reward`.
    With the defaults the near (left) exit pays little and the far (right) exit pays more, so a planner has to
    look several steps ahead to choose well.
    """

    def __init__(self, length: int = 7, start: int = 2, left_reward: float = 0.3, right_reward: float = 1.0) -> None:
        self.length, self.start = length, start
        self.left_reward, self.right_reward = left_reward, right_reward

    def legal_actions(self, state: int) -> list[int]:
        return [0, 1]

    def step(self, state: int, action: int):
        nxt = state - 1 if action == 0 else state + 1
        if nxt == 0:
            return nxt, self.left_reward, True
        if nxt == self.length - 1:
            return nxt, self.right_reward, True
        return nxt, 0.0, False


class PointMassModel:
    """Batched double integrator: state (position, velocity), action = force in [-1, 1].

    velocity += dt * force; position += dt * velocity. Reward is -(position^2 + 0.1 * velocity^2 + 0.01 * force^2)
    of the state reached, so the best plan drives the mass to rest at the origin.
    """

    def __init__(self, dt: float = 0.2) -> None:
        self.dt = dt

    def dynamics(self, states: np.ndarray, actions: np.ndarray) -> np.ndarray:
        """states (N, 2), actions (N, 1) -> next states (N, 2)."""
        vel = states[:, 1] + self.dt * actions[:, 0]
        pos = states[:, 0] + self.dt * vel
        return np.stack([pos, vel], axis=1)

    def reward(self, states: np.ndarray, actions: np.ndarray, next_states: np.ndarray) -> np.ndarray:
        """Returns rewards of shape (N,)."""
        return -(next_states[:, 0] ** 2 + 0.1 * next_states[:, 1] ** 2 + 0.01 * actions[:, 0] ** 2)


class _Node:
    """One state in the search tree. `total` sums the returns of simulations that took the action leading here."""

    __slots__ = ("state", "reward", "done", "children", "untried", "visits", "total")

    def __init__(self, state, reward: float, done: bool, actions: list) -> None:
        self.state, self.reward, self.done = state, reward, done
        self.children: dict = {}
        self.untried = list(actions)
        self.visits = 0
        self.total = 0.0


class MCTS:
    """UCT: tree search that balances the average return of each action against how rarely it was tried."""

    def __init__(self, config: PlanningConfig | None, model) -> None:
        self.config = config or PlanningConfig()
        self.model = model
        self.rng = np.random.default_rng(self.config.seed)
        self.root: _Node | None = None

    def _rollout(self, state, done: bool) -> float:
        """Discounted return of a uniformly random walk from `state`, at most `rollout_depth` steps."""
        total, discount = 0.0, 1.0
        for _ in range(self.config.rollout_depth):
            if done:
                break
            actions = self.model.legal_actions(state)
            state, reward, done = self.model.step(state, actions[int(self.rng.integers(len(actions)))])
            total += discount * reward
            discount *= self.config.gamma
        return total

    def _select_child(self, node: _Node):
        log_n = math.log(node.visits)
        best, best_score = None, -math.inf
        for child in node.children.values():
            score = child.total / child.visits + self.config.c_uct * math.sqrt(log_n / child.visits)
            if score > best_score:
                best, best_score = child, score
        return best

    def _simulate(self, root: _Node) -> None:
        path, node = [root], root
        while not node.done and not node.untried:  # selection
            node = self._select_child(node)
            path.append(node)
        if not node.done:  # expansion
            action = node.untried.pop(int(self.rng.integers(len(node.untried))))
            state, reward, done = self.model.step(node.state, action)
            child = _Node(state, reward, done, [] if done else self.model.legal_actions(state))
            node.children[action] = child
            node = child
            path.append(node)
        value = self._rollout(node.state, node.done)  # value of the leaf state, 0 if terminal
        for node in reversed(path):  # backup: each node records reward + gamma * value of what followed
            value = node.reward + self.config.gamma * value
            node.visits += 1
            node.total += value

    def search(self, state):
        """Run `n_simulations` from `state` and return the most visited root action."""
        self.root = _Node(state, 0.0, False, self.model.legal_actions(state))
        for _ in range(self.config.n_simulations):
            self._simulate(self.root)
        return max(self.root.children.items(), key=lambda kv: kv[1].visits)[0]

    def action_values(self) -> dict:
        """Average return of each root action tried by the last search."""
        return {a: c.total / c.visits for a, c in self.root.children.items()}

    def visit_counts(self) -> dict:
        """Number of simulations that started with each root action in the last search."""
        return {a: c.visits for a, c in self.root.children.items()}


def rollout_returns(dynamics_fn: Callable, reward_fn: Callable, state: np.ndarray, action_seqs: np.ndarray,
                    gamma: float = 1.0) -> np.ndarray:
    """Discounted return of every action sequence, all started from the same state.

    state: (state_dim,). action_seqs: (N, horizon, action_dim). Returns shape (N,).
    """
    n, horizon, _ = action_seqs.shape
    states = np.repeat(np.asarray(state, dtype=float)[None], n, axis=0)
    returns, discount = np.zeros(n), 1.0
    for t in range(horizon):
        actions = action_seqs[:, t]
        next_states = dynamics_fn(states, actions)
        returns += discount * reward_fn(states, actions, next_states)
        discount *= gamma
        states = next_states
    return returns


def random_shooting(dynamics_fn: Callable, reward_fn: Callable, state: np.ndarray, config: PlanningConfig,
                    rng: np.random.Generator) -> tuple[np.ndarray, float]:
    """Sample `population` uniform action sequences and return the best one with its return.

    Returns (plan (horizon, action_dim), predicted return).
    """
    seqs = rng.uniform(config.action_low, config.action_high, size=(config.population, config.horizon, config.action_dim))
    returns = rollout_returns(dynamics_fn, reward_fn, state, seqs, config.gamma)
    best = int(returns.argmax())
    return seqs[best], float(returns[best])


def cem_plan(dynamics_fn: Callable, reward_fn: Callable, state: np.ndarray, config: PlanningConfig,
             rng: np.random.Generator, init_mean: np.ndarray | None = None) -> tuple[np.ndarray, float]:
    """Cross-entropy method over action sequences.

    Each iteration samples `population` sequences from a diagonal Gaussian (clipped to the action bounds), scores
    them with the model and refits mean and standard deviation to the `n_elites` best.
    init_mean: optional starting mean, shape (horizon, action_dim).
    Returns (plan (horizon, action_dim) = final mean, its predicted return).
    """
    shape = (config.horizon, config.action_dim)
    mean = np.full(shape, 0.5 * (config.action_low + config.action_high)) if init_mean is None else np.array(init_mean, dtype=float)
    std = np.full(shape, config.init_std * (config.action_high - config.action_low))
    for _ in range(config.cem_iterations):
        seqs = np.clip(mean + std * rng.standard_normal((config.population, *shape)), config.action_low, config.action_high)
        returns = rollout_returns(dynamics_fn, reward_fn, state, seqs, config.gamma)
        elites = seqs[np.argsort(returns)[-config.n_elites:]]
        mean, std = elites.mean(axis=0), elites.std(axis=0) + 1e-6
    return mean, float(rollout_returns(dynamics_fn, reward_fn, state, mean[None], config.gamma)[0])


class MPCController:
    """Model-predictive control: plan `horizon` steps ahead, apply the first action, plan again next step."""

    def __init__(self, config: PlanningConfig | None, dynamics_fn: Callable, reward_fn: Callable) -> None:
        self.config = config or PlanningConfig()
        self.dynamics_fn, self.reward_fn = dynamics_fn, reward_fn
        self.rng = np.random.default_rng(self.config.seed)
        self.plan: np.ndarray | None = None
        self.predicted_return = 0.0

    def reset(self) -> None:
        """Forget the previous plan (call at the start of an episode)."""
        self.plan = None

    def act(self, state: np.ndarray) -> np.ndarray:
        """Return the action to apply in `state`, shape (action_dim,)."""
        c = self.config
        if c.planner == "random_shooting":
            self.plan, self.predicted_return = random_shooting(self.dynamics_fn, self.reward_fn, state, c, self.rng)
        else:
            warm = None
            if self.plan is not None:  # shift the last plan one step and repeat its final action
                warm = np.concatenate([self.plan[1:], self.plan[-1:]], axis=0)
            self.plan, self.predicted_return = cem_plan(self.dynamics_fn, self.reward_fn, state, c, self.rng, warm)
        return self.plan[0].copy()
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
11, run with python3 -m unittest -v

Practice

Run mcts = MCTS(PlanningConfig(), CorridorModel()), call mcts.search(2), and read mcts.action_values() and mcts.visit_counts(). Repeat with n_simulations=10 and with rollout_depth=1 and explain the changes. Then drive PointMassModel from state (1, 0) for 30 steps with MPCController(PlanningConfig(), model.dynamics, model.reward), once with the default planner and once with planner set to random_shooting, and compare total reward.

Check on learning

  1. With rollout_depth set to 1 in the corridor, what can a rollout from cell 3 learn about the right exit? How does the tree compensate as simulations accumulate?
    A way to think about it

    A rollout that short ends before any reward. But the tree itself grows one node per simulation, so ask how deep it gets after 200 of them.

  2. search returns the most visited action, not the one with the highest average return. When could those differ, and why is the visit count the safer choice?
    A way to think about it

    An action tried twice can have a lucky high average. Think about how many samples stand behind each number.

  3. For a horizon of 15 and one action dimension, random shooting searches a 15-dimensional space with 200 samples. Why does CEM do better with the same number of samples per round?
    A way to think about it

    Uniform samples stay spread over the whole space every time. Follow what happens to where CEM's samples fall in the second and third rounds.

  4. MPC replans at every step even though it already has a full plan. If the model were perfect and the environment had no noise, would replanning still help?
    A way to think about it

    A plan covers only the next HH steps. Consider what the agent knows at step 1 about step H+1H + 1 that it did not know at step 0.

  5. You hand these planners a learned model that is accurate near the training data and wrong elsewhere. Why might a stronger planner give worse real results than a weaker one?
    A way to think about it

    A planner searches for the highest predicted return. Ask where a model's largest overestimates are likely to be, and which planner is better at finding them.