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
MCTS.searchrunsn_simulationsdescents from the current state. Each descent follows the UCT rule down the tree until it reaches a node with an untried action.- 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_depthsteps. - 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.
searchreturns the most visited root action. rollout_returnstakes a batch of action sequences and computes the discounted return of each under a batched dynamics function and reward function.random_shootingsamplespopulationsequences uniformly within the action bounds and returns the best one.cem_plansamples sequences from a Gaussian, refits the Gaussian to then_elitesbest, repeatscem_iterationstimes, and returns the final mean.MPCController.actplans, 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
| If | Use instead |
|---|---|
| No model exists and one must be learned from data | PETS or MBPO |
| You want the search to improve itself through learning | AlphaZero, or MuZero if the rules are unknown |
| Decisions must be instant at run time | A learned policy such as PPO or SAC |
Math foundations
What every planner maximizes
The discounted return of an action sequence when the model is stepped forward from the current state.
rollout_returnscomputes this for many sequences at once.UCT selection
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.
Backup along the path
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 is added to the node's total .
Random shooting
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.
Cross-entropy method
Guess, then learn from the guesses: sample from a Gaussian over sequences, keep the best, and move the Gaussian onto them. After a few rounds the samples cluster around a good plan.
Receding horizon and warm start
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
- state and action at step t of an imagined rollout
- the given dynamics model and reward function
- planning horizon in steps
- discount factor
- discounted return of an action sequence
- visits to a tree node, and to its child for action a
- sum of the returns backed up through action a
- exploration constant of the UCT rule (c_uct)
- return being passed up the tree
- the i-th sampled action sequence, of shape horizon by action dimension d
- sequences sampled per round (population) and elites kept (n_elites)
- 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 . Then apply UCT at a root with 20 visits and , where left has mean 0.3 over 15 visits and right has mean 0.5 over 5 visits.
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
- With
rollout_depthset 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.
searchreturns 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.
- 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.
- 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 steps. Consider what the agent knows at step 1 about step that it did not know at step 0.
- 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.