Skip to main content

game_tree_search/
mcts.rs

1//! Monte Carlo tree search (MCTS): a tree grown by random simulations instead of a full
2//! search to a fixed depth.
3
4mod batch;
5mod gumbel;
6#[cfg(feature = "parallel")]
7mod parallel;
8mod policy;
9mod random;
10mod selfplay;
11#[cfg(feature = "parallel")]
12mod shared;
13mod tree;
14
15use alloc::vec::Vec;
16
17use search_core::Budget;
18
19pub use gumbel::Gumbel;
20pub use policy::{
21    BatchEvaluator, BatchLeaf, Evaluation, Evaluator, NodeStats, Puct, Rollout, Selection,
22    StaticValue, Uct, Unbatched,
23};
24#[cfg(feature = "rand_core")]
25pub use random::RandCore;
26pub use random::{Random, SplitMix64};
27pub use selfplay::RootNoise;
28use tree::Tree;
29
30use crate::Game;
31
32/// A game whose scores map to rewards, as Monte Carlo tree search averages them.
33pub trait Rewarded: Game {
34    /// [`Side::Max`](crate::Side::Max)'s reward for `score`, in `[0, 1]`: `1` is the best
35    /// outcome for [`Side::Max`](crate::Side::Max), `0` the best for
36    /// [`Side::Min`](crate::Side::Min). For a win, a draw and a loss, `1`, `0.5` and `0`.
37    fn reward(&self, score: Self::Score) -> f64;
38}
39
40/// Counters of one Monte Carlo tree search, which its [`Budget`] sees.
41///
42/// Non-exhaustive: later versions may add counters. Start from [`TreeStats::default`].
43#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct TreeStats {
46    /// Simulations run: selection, one leaf evaluation and the backup.
47    pub simulations: u64,
48    /// Nodes in the tree, the root included; each holds one position's statistics.
49    pub nodes: u64,
50    /// The depth of the deepest node, counted in moves from the root.
51    pub depth: u32,
52}
53
54/// A root move with the statistics of the simulations through it.
55///
56/// Non-exhaustive: later versions may report more per move.
57#[derive(Debug, Clone, PartialEq)]
58#[non_exhaustive]
59pub struct MoveStats<M> {
60    /// The move.
61    pub mv: M,
62    /// Simulations that started with the move.
63    pub visits: u32,
64    /// The sum of [`Side::Max`](crate::Side::Max)'s rewards over those simulations.
65    pub value: f64,
66}
67
68impl<M> MoveStats<M> {
69    /// [`Side::Max`](crate::Side::Max)'s mean reward after the move; `0.5` if unvisited.
70    #[must_use]
71    pub fn mean(&self) -> f64 {
72        if self.visits == 0 {
73            0.5
74        } else {
75            self.value / f64::from(self.visits)
76        }
77    }
78}
79
80/// The result of a Monte Carlo tree search.
81///
82/// Non-exhaustive: later versions may report more.
83#[derive(Debug, Clone, PartialEq)]
84#[non_exhaustive]
85pub struct MctsResult<M> {
86    /// The move with the most visits, ties going to the earliest; with no simulations, the
87    /// first move. `None` if the root has no moves.
88    pub best: Option<M>,
89    /// Every root move in move order, with its visits and value.
90    ///
91    /// The visit counts divided by [`TreeStats::simulations`] are the search's move
92    /// distribution, and the stats of several searches, for example over sampled deals of
93    /// hidden cards, can be added up move by move. Not after [`Mcts::search_gumbel`]: its
94    /// visits follow the halving schedule, and its move distribution is
95    /// [`MctsResult::improved`].
96    pub root: Vec<MoveStats<M>>,
97    /// The most visited line: from the root, the most visited child of each node, while it
98    /// was visited.
99    pub pv: Vec<M>,
100    /// [`Side::Max`](crate::Side::Max)'s mean reward at the root over all its simulations, in
101    /// `[0, 1]`; `0.5` before the first. The search's value of the position, as a self-play
102    /// training target.
103    pub value: f64,
104    /// The improved policy over [`MctsResult::root`] that
105    /// [`Mcts::search_gumbel`] computes, in move order and summing to one: the training
106    /// target of a Gumbel search, whose visit counts follow its halving schedule rather than
107    /// the policy. `None` for every other search; [`MctsResult::policy`] returns it when set.
108    pub improved: Option<Vec<f64>>,
109    /// What the search did.
110    pub stats: TreeStats,
111}
112
113/// Monte Carlo tree search with replaceable selection, leaf evaluation and random source.
114///
115/// Each simulation descends from the root, choosing unvisited children first and then by
116/// the [`Selection`] rule for the side to move at each node, so one side may move several
117/// times in a row. It adds the first unvisited node it reaches, values it with the
118/// [`Evaluator`] and adds the reward to every node on the way (mean backup). A position
119/// without moves is valued by its [`Rewarded::reward`].
120///
121/// The defaults are [`Uct`] selection, [`Rollout`] playouts and a [`SplitMix64`] generator seeded
122/// with `0`; with the `rand_core` feature, `RandCore` wraps any `rand_core` generator. With the
123/// `parallel` feature, `Mcts::search_parallel` runs several trees on `std` threads and adds up
124/// their root statistics. The generator continues across searches, so a searcher reproduces the
125/// same sequence of searches from the same seed. The tree is rebuilt for every search, in buffers
126/// kept between searches. Chance positions of [`Stochastic`](crate::Stochastic) games are not
127/// sampled: MCTS sees only [`Game::moves`].
128///
129/// # Examples
130///
131/// ```
132/// # use game_tree_search::{Game, Side};
133/// # struct Nim;
134/// # impl Game for Nim {
135/// #     type Position = (u32, Side);
136/// #     type Move = u32;
137/// #     type Score = i32;
138/// #     fn side_to_move(&self, &(_, side): &Self::Position) -> Side { side }
139/// #     fn moves(&self, &(stones, _): &Self::Position, moves: &mut Vec<u32>) {
140/// #         moves.extend((1..=2).filter(|&take| take <= stones));
141/// #     }
142/// #     fn play(&self, &(stones, side): &Self::Position, take: &u32) -> Self::Position {
143/// #         (stones - take, if side == Side::Max { Side::Min } else { Side::Max })
144/// #     }
145/// #     fn evaluate(&self, &(stones, side): &Self::Position) -> i32 {
146/// #         match (stones, side) { (0, Side::Max) => -1, (0, Side::Min) => 1, _ => 0 }
147/// #     }
148/// # }
149/// use game_tree_search::{Mcts, Rewarded, TreeStats};
150///
151/// impl Rewarded for Nim {
152///     fn reward(&self, score: i32) -> f64 {
153///         f64::from(score + 1) / 2.0
154///     }
155/// }
156///
157/// // Seven stones: taking one leaves six, a lost pile for the opponent.
158/// let mut mcts = Mcts::new();
159/// let result = mcts.search(&Nim, &(7, Side::Max), |stats: &TreeStats| stats.simulations >= 2000);
160/// assert_eq!(result.best, Some(1));
161/// assert_eq!(result.root.iter().map(|root| root.visits).sum::<u32>(), 2000);
162/// ```
163#[derive(Debug)]
164pub struct Mcts<G: Game, E = Rollout<<G as Game>::Move>, S = Uct, R = SplitMix64> {
165    /// Values new leaves.
166    evaluator: E,
167    /// Chooses among visited children.
168    selection: S,
169    /// Draws the random numbers.
170    rng: R,
171    /// The search tree, kept for its capacity.
172    tree: Tree<G::Move>,
173    /// Dirichlet noise mixed into the root's priors at the start of each search, if any.
174    noise: Option<RootNoise>,
175}
176
177impl<G: Rewarded> Mcts<G> {
178    /// A search with [`Uct`] selection, [`Rollout`] playouts of up to 100 moves and a
179    /// [`SplitMix64`] generator seeded with `0`.
180    #[must_use]
181    pub fn new() -> Self {
182        Self {
183            evaluator: Rollout::default(),
184            selection: Uct::default(),
185            rng: SplitMix64::new(0),
186            tree: Tree::new(),
187            noise: None,
188        }
189    }
190}
191
192impl<G: Rewarded> Default for Mcts<G> {
193    fn default() -> Self {
194        Self::new()
195    }
196}
197
198impl<G: Rewarded, E: Evaluator<G>, S: Selection, R: Random> Mcts<G, E, S, R> {
199    /// This search, valuing new leaves with `evaluator`.
200    #[must_use]
201    pub fn with_evaluator<E2: Evaluator<G>>(self, evaluator: E2) -> Mcts<G, E2, S, R> {
202        Mcts {
203            evaluator,
204            selection: self.selection,
205            rng: self.rng,
206            tree: self.tree,
207            noise: self.noise,
208        }
209    }
210
211    /// This search, choosing children with `selection`.
212    #[must_use]
213    pub fn with_selection<S2: Selection>(self, selection: S2) -> Mcts<G, E, S2, R> {
214        Mcts {
215            evaluator: self.evaluator,
216            selection,
217            rng: self.rng,
218            tree: self.tree,
219            noise: self.noise,
220        }
221    }
222
223    /// This search, mixing Dirichlet `noise` into the root's move priors at the start of
224    /// every search, as in `AlphaZero`-style self-play.
225    ///
226    /// The noise is drawn from the searcher's generator, so a seed still reproduces a
227    /// search. Only selection rules that read priors, such as [`Puct`], notice it. A
228    /// `fraction` of `0` draws nothing, so the search is exactly the one without noise. With tree
229    /// reuse, the new root's priors are noised for the first time; [`Mcts::advance`] with no
230    /// moves keeps the root, and its priors are noised again.
231    ///
232    /// # Panics
233    ///
234    /// Panics if `noise` is not [`RootNoise::is_valid`]: an `alpha` that is not finite and
235    /// positive, or a `fraction` outside `[0, 1]`.
236    #[must_use]
237    pub fn with_root_noise(mut self, noise: RootNoise) -> Self {
238        assert!(
239            noise.is_valid(),
240            "root noise needs a finite, positive alpha and a fraction in [0, 1]: {noise:?}"
241        );
242        self.noise = Some(noise);
243        self
244    }
245
246    /// Mixes the configured noise, if any, into the root's priors.
247    fn add_root_noise(&mut self) {
248        if let Some(noise) = self.noise {
249            self.tree.noise_root(&noise, &mut self.rng);
250        }
251    }
252
253    /// This search, drawing random numbers from `rng`.
254    #[must_use]
255    pub fn with_rng<R2: Random>(self, rng: R2) -> Mcts<G, E, S, R2> {
256        Mcts {
257            evaluator: self.evaluator,
258            selection: self.selection,
259            rng,
260            tree: self.tree,
261            noise: self.noise,
262        }
263    }
264
265    /// Searches `position`, running simulations until `budget` is exhausted.
266    ///
267    /// The budget is asked before every simulation, so a limit of `n` simulations runs
268    /// exactly `n`. Bound memory by also limiting [`TreeStats::nodes`].
269    ///
270    /// After [`Mcts::advance`] kept a subtree, the search continues from it if `position`
271    /// fits it: the same side to move and the same moves in the same order. Otherwise, for
272    /// example for the root of a new game, it starts a new tree.
273    /// [`TreeStats::simulations`] counts this search's simulations only, while the root
274    /// moves' visits include the kept ones.
275    pub fn search(
276        &mut self,
277        game: &G,
278        position: &G::Position,
279        mut budget: impl Budget<TreeStats>,
280    ) -> MctsResult<G::Move> {
281        self.tree.begin(game, position, &mut self.evaluator);
282        self.add_root_noise();
283        while !budget.exhausted(&self.tree.stats) {
284            self.simulate(game, position);
285        }
286
287        self.tree.result()
288    }
289
290    /// Keeps the subtree under `moves`, played from the last search's root, for the next
291    /// search to continue from (tree reuse), and drops the rest of the tree.
292    ///
293    /// Typically the move the search chose and the opponent's reply. Returns whether a
294    /// subtree was kept: not if a move is not in the tree, or if the position it leads to was
295    /// never visited; the next search then starts a new tree, as without this call. Only
296    /// [`Mcts::search`] and [`Mcts::search_batched`] continue a kept tree; with the
297    /// `parallel` feature, `Mcts::search_parallel` always starts new trees.
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// # use game_tree_search::{Game, Side};
303    /// # struct Nim;
304    /// # impl Game for Nim {
305    /// #     type Position = (u32, Side);
306    /// #     type Move = u32;
307    /// #     type Score = i32;
308    /// #     fn side_to_move(&self, &(_, side): &Self::Position) -> Side { side }
309    /// #     fn moves(&self, &(stones, _): &Self::Position, moves: &mut Vec<u32>) {
310    /// #         moves.extend((1..=2).filter(|&take| take <= stones));
311    /// #     }
312    /// #     fn play(&self, &(stones, side): &Self::Position, take: &u32) -> Self::Position {
313    /// #         (stones - take, if side == Side::Max { Side::Min } else { Side::Max })
314    /// #     }
315    /// #     fn evaluate(&self, &(stones, side): &Self::Position) -> i32 {
316    /// #         match (stones, side) { (0, Side::Max) => -1, (0, Side::Min) => 1, _ => 0 }
317    /// #     }
318    /// # }
319    /// # impl game_tree_search::Rewarded for Nim {
320    /// #     fn reward(&self, score: i32) -> f64 { f64::from(score + 1) / 2.0 }
321    /// # }
322    /// use game_tree_search::{Mcts, TreeStats};
323    ///
324    /// let budget = |stats: &TreeStats| stats.simulations >= 1000;
325    /// let mut mcts = Mcts::new();
326    /// let first = mcts.search(&Nim, &(10, Side::Max), budget);
327    /// assert_eq!(first.best, Some(1));
328    ///
329    /// // Max takes 1, Min takes 2: keep what the search learned about the 7 stones left.
330    /// assert!(mcts.advance(&[1, 2]));
331    /// let second = mcts.search(&Nim, &(7, Side::Max), budget);
332    /// let kept: u32 = second.root.iter().map(|root| root.visits).sum();
333    /// assert!(kept > 1000);
334    /// assert_eq!(second.best, Some(1));
335    /// ```
336    pub fn advance(&mut self, moves: &[G::Move]) -> bool {
337        self.tree.advance(moves)
338    }
339
340    /// One simulation from the root `position`: select, expand, evaluate, back up.
341    fn simulate(&mut self, game: &G, position: &G::Position) {
342        let leaf = self
343            .tree
344            .select(game, position, (&self.selection, &mut self.evaluator));
345        let value = self.leaf_value(game, position, &leaf);
346        self.tree.backup(value);
347    }
348
349    /// [`Side::Max`](crate::Side::Max)'s reward at the simulation's `leaf`, below `root`:
350    /// the game's own where it ends, the evaluator's otherwise.
351    fn leaf_value(&mut self, game: &G, root: &G::Position, leaf: &tree::Leaf<G::Position>) -> f64 {
352        let reached = leaf.position.as_ref().unwrap_or(root);
353        if leaf.finished {
354            game.reward(game.evaluate(reached))
355        } else {
356            self.evaluator.evaluate(game, reached, &mut self.rng).value
357        }
358    }
359}