game_tree_search/mcts/policy.rs
1//! The plug points of Monte Carlo tree search: how a child is selected ([`Selection`],
2//! default [`Uct`]) and how a new leaf is valued ([`Evaluator`], default [`Rollout`]).
3
4use alloc::vec::Vec;
5
6use super::Rewarded;
7use super::random::Random;
8use crate::Side;
9
10/// What a search knows about one node of its tree, as selection sees it.
11///
12/// Non-exhaustive: later selection rules may need more, such as pending evaluations.
13#[derive(Debug, Clone, Copy, PartialEq)]
14#[non_exhaustive]
15pub struct NodeStats {
16 /// Simulations that passed through the node; stops counting at `u32::MAX`.
17 pub visits: u32,
18 /// The sum of [`Side::Max`]'s rewards over those simulations, each in `[0, 1]`.
19 pub value: f64,
20 /// The node's prior probability among its siblings, from [`Evaluator::priors`];
21 /// uniform unless the evaluator gives priors.
22 pub prior: f64,
23}
24
25impl NodeStats {
26 /// The mean reward for `side`: [`Side::Max`]'s mean, or one minus it for
27 /// [`Side::Min`]. `0.5` before the first visit.
28 #[must_use]
29 pub fn mean_for(&self, side: Side) -> f64 {
30 if self.visits == 0 {
31 return 0.5;
32 }
33
34 let max = self.value / f64::from(self.visits);
35 match side {
36 Side::Max => max,
37 Side::Min => 1.0 - max,
38 }
39 }
40}
41
42/// Chooses which visited child a simulation descends into.
43///
44/// By default, children never visited are tried first, in move order, so a rule only scores
45/// visited children (see [`Selection::unvisited_first`]); the highest score wins, ties
46/// going to the earliest child.
47pub trait Selection {
48 /// The score of `child` for `side`, who moves at `parent`.
49 fn score(&self, side: Side, parent: &NodeStats, child: &NodeStats) -> f64;
50
51 /// Whether unvisited children are tried first, in move order, before any is scored.
52 ///
53 /// The default, `true`, suits rules like [`Uct`] that cannot score an unvisited child.
54 /// A rule that can, like [`Puct`], returns `false` and scores every child.
55 fn unvisited_first(&self) -> bool {
56 true
57 }
58}
59
60/// Upper confidence bounds applied to trees (UCT, Kocsis and Szepesvári 2006): the child's
61/// mean for the side to move plus `exploration * sqrt(ln(parent visits) / child visits)`.
62#[derive(Debug, Clone, Copy, PartialEq)]
63pub struct Uct {
64 /// The exploration constant `c`, finite and non-negative. `sqrt(2)` suits rewards in
65 /// `[0, 1]`; larger values explore more.
66 pub exploration: f64,
67}
68
69impl Default for Uct {
70 fn default() -> Self {
71 Self {
72 exploration: core::f64::consts::SQRT_2,
73 }
74 }
75}
76
77impl Selection for Uct {
78 fn score(&self, side: Side, parent: &NodeStats, child: &NodeStats) -> f64 {
79 let parent = f64::from(parent.visits.max(1));
80 let visits = f64::from(child.visits.max(1));
81
82 child.mean_for(side) + self.exploration * libm::sqrt(libm::log(parent) / visits)
83 }
84}
85
86/// Predictor-UCT (PUCT, Rosin 2011; as in `AlphaGo` Zero and `AlphaZero`): the child's mean for
87/// the side to move plus `c_puct * prior * sqrt(parent visits) / (1 + child visits)`.
88///
89/// Unlike [`Uct`], it scores unvisited children too, at a mean of `0.5`, so priors decide
90/// which moves are tried at all. Priors come from [`Evaluator::priors`]; without them they
91/// are uniform, and PUCT explores evenly.
92#[derive(Debug, Clone, Copy, PartialEq)]
93pub struct Puct {
94 /// The exploration constant `c_puct`, finite and non-negative; `1.25` by default, as in
95 /// the `MuZero` pseudocode.
96 pub c_puct: f64,
97}
98
99impl Default for Puct {
100 fn default() -> Self {
101 Self { c_puct: 1.25 }
102 }
103}
104
105impl Selection for Puct {
106 fn score(&self, side: Side, parent: &NodeStats, child: &NodeStats) -> f64 {
107 let parent = libm::sqrt(f64::from(parent.visits));
108 let exploration = child.prior * parent / (1.0 + f64::from(child.visits));
109
110 child.mean_for(side) + self.c_puct * exploration
111 }
112
113 fn unvisited_first(&self) -> bool {
114 false
115 }
116}
117
118/// What an [`Evaluator`] found out about a new leaf.
119///
120/// Non-exhaustive: later evaluators may also return move priors.
121#[derive(Debug, Clone, Copy, PartialEq)]
122#[non_exhaustive]
123pub struct Evaluation {
124 /// [`Side::Max`]'s reward from the leaf, in `[0, 1]`.
125 pub value: f64,
126}
127
128impl Evaluation {
129 /// An evaluation of `value`, [`Side::Max`]'s reward in `[0, 1]`.
130 #[must_use]
131 pub const fn new(value: f64) -> Self {
132 Self { value }
133 }
134}
135
136/// Values a leaf the first time a simulation reaches it.
137pub trait Evaluator<G: Rewarded> {
138 /// The value of `position`, drawing from `rng` if needed.
139 fn evaluate<R: Random>(&mut self, game: &G, position: &G::Position, rng: &mut R) -> Evaluation;
140
141 /// Appends a prior for each of `moves`, the moves of `position` in search order, to
142 /// `priors`, which arrives empty: how promising each move looks, such as a policy
143 /// network's output.
144 ///
145 /// Asked once when a node is expanded. The search scales the priors to sum to one;
146 /// appending none, or a wrong number, negative or non-finite values or only zeros, leaves
147 /// them uniform. The default appends none. Only selection rules that read
148 /// [`NodeStats::prior`], such as [`Puct`], use them.
149 fn priors(
150 &mut self,
151 game: &G,
152 position: &G::Position,
153 moves: &[G::Move],
154 priors: &mut Vec<f64>,
155 ) {
156 let _ = (game, position, moves, priors);
157 }
158}
159
160/// A new leaf of a batch, as a [`BatchEvaluator`] sees it.
161///
162/// Non-exhaustive: later versions may pass more per leaf.
163#[derive(Debug, Clone, Copy)]
164#[non_exhaustive]
165pub struct BatchLeaf<'a, P, M> {
166 /// The leaf's position.
167 pub position: &'a P,
168 /// The leaf's moves, in search order; a prior is wanted for each.
169 pub moves: &'a [M],
170}
171
172/// Values several new leaves in one call, as a neural network on a GPU wants to; see
173/// `Mcts::search_batched`.
174pub trait BatchEvaluator<G: Rewarded> {
175 /// Values every leaf of `leaves`, appending to `values`, which arrives empty,
176 /// [`Side::Max`]'s reward in `[0, 1]` per leaf, in order. May also append to `priors`,
177 /// which arrives empty, a prior for every move of every leaf, leaf after leaf.
178 ///
179 /// A missing value counts as `0.5`. Priors of the wrong total length are ignored, and a
180 /// leaf's priors are scaled to sum to one, or made uniform if invalid; without priors,
181 /// the leaves keep the priors their expansion gave them.
182 fn evaluate_batch(
183 &mut self,
184 game: &G,
185 leaves: &[BatchLeaf<'_, G::Position, G::Move>],
186 values: &mut Vec<f64>,
187 priors: &mut Vec<f64>,
188 );
189}
190
191/// An [`Evaluator`] used one leaf at a time as a [`BatchEvaluator`], with its own generator:
192/// for testing a batched setup, or for evaluators that gain nothing from batches.
193#[derive(Debug, Clone)]
194pub struct Unbatched<E, R = super::random::SplitMix64> {
195 /// The evaluator asked for every leaf.
196 pub evaluator: E,
197 /// The generator the evaluator draws from.
198 pub rng: R,
199}
200
201impl<E> Unbatched<E> {
202 /// `evaluator`, used leaf by leaf with a [`SplitMix64`](super::random::SplitMix64) seeded
203 /// with `seed`.
204 #[must_use]
205 pub const fn new(evaluator: E, seed: u64) -> Self {
206 Self {
207 evaluator,
208 rng: super::random::SplitMix64::new(seed),
209 }
210 }
211}
212
213impl<G: Rewarded, E: Evaluator<G>, R: Random> BatchEvaluator<G> for Unbatched<E, R> {
214 fn evaluate_batch(
215 &mut self,
216 game: &G,
217 leaves: &[BatchLeaf<'_, G::Position, G::Move>],
218 values: &mut Vec<f64>,
219 priors: &mut Vec<f64>,
220 ) {
221 for leaf in leaves {
222 values.push(
223 self.evaluator
224 .evaluate(game, leaf.position, &mut self.rng)
225 .value,
226 );
227 }
228
229 let mut own = Vec::new();
230 for leaf in leaves {
231 own.clear();
232 self.evaluator
233 .priors(game, leaf.position, leaf.moves, &mut own);
234 if own.len() != leaf.moves.len() {
235 priors.clear();
236 return;
237 }
238
239 priors.extend_from_slice(&own);
240 }
241 }
242}
243
244/// Random playout: random moves until the game ends or `max_plies` were played, then the
245/// [`reward`](Rewarded::reward) of the position reached.
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct Rollout<M> {
248 /// The most moves one playout plays before it scores the position.
249 pub max_plies: u32,
250 /// The move list, kept for its capacity.
251 moves: Vec<M>,
252}
253
254impl<M> Rollout<M> {
255 /// Playouts of at most `max_plies` moves.
256 #[must_use]
257 pub const fn new(max_plies: u32) -> Self {
258 Self {
259 max_plies,
260 moves: Vec::new(),
261 }
262 }
263}
264
265impl<M> Default for Rollout<M> {
266 /// Playouts of at most 100 moves.
267 fn default() -> Self {
268 Self::new(100)
269 }
270}
271
272impl<G: Rewarded> Evaluator<G> for Rollout<G::Move> {
273 fn evaluate<R: Random>(&mut self, game: &G, position: &G::Position, rng: &mut R) -> Evaluation {
274 let mut moves = core::mem::take(&mut self.moves);
275 let mut current = None;
276 for _ in 0..self.max_plies {
277 let here = current.as_ref().unwrap_or(position);
278 moves.clear();
279 game.moves(here, &mut moves);
280 if moves.is_empty() {
281 break;
282 }
283
284 let mv = &moves[rng.below(moves.len())];
285 current = Some(game.play(here, mv));
286 }
287
288 moves.clear();
289 self.moves = moves;
290 let leaf = current.as_ref().unwrap_or(position);
291 Evaluation::new(game.reward(game.evaluate(leaf)))
292 }
293}
294
295/// The game's own evaluation as the leaf value, without playing on: the
296/// [`reward`](Rewarded::reward) of [`evaluate`](crate::Game::evaluate).
297///
298/// Cheaper than a [`Rollout`] and deterministic; as good as the evaluation is.
299#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
300pub struct StaticValue;
301
302impl<G: Rewarded> Evaluator<G> for StaticValue {
303 fn evaluate<R: Random>(&mut self, game: &G, position: &G::Position, _: &mut R) -> Evaluation {
304 Evaluation::new(game.reward(game.evaluate(position)))
305 }
306}
307
308/// Unit tests for the node means and UCT scores.
309#[cfg(test)]
310mod tests {
311 use super::{NodeStats, Selection, Uct};
312 use crate::Side;
313
314 /// Node statistics with `visits` and `value`.
315 const fn stats(visits: u32, value: f64) -> NodeStats {
316 NodeStats {
317 visits,
318 value,
319 prior: 1.0,
320 }
321 }
322
323 /// Means are from the asking side's point of view, and one half before any visit.
324 #[test]
325 fn means_belong_to_the_side_to_move() {
326 assert!((stats(4, 3.0).mean_for(Side::Max) - 0.75).abs() < 1e-12);
327 assert!((stats(4, 3.0).mean_for(Side::Min) - 0.25).abs() < 1e-12);
328 assert!((stats(0, 0.0).mean_for(Side::Max) - 0.5).abs() < 1e-12);
329 }
330
331 /// UCT favours the less visited of two equally good children, and none without
332 /// exploration.
333 #[test]
334 fn uct_explores_the_less_visited_child() {
335 let parent = stats(20, 10.0);
336 let uct = Uct::default();
337 let (rare, common) = (stats(2, 1.0), stats(18, 9.0));
338 assert!(uct.score(Side::Max, &parent, &rare) > uct.score(Side::Max, &parent, &common));
339
340 let greedy = Uct { exploration: 0.0 };
341 let gap =
342 greedy.score(Side::Max, &parent, &rare) - greedy.score(Side::Max, &parent, &common);
343 assert!(gap.abs() < 1e-12);
344 }
345}