use alloc::vec::Vec;
use super::Rewarded;
use super::random::Random;
use crate::Side;
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct NodeStats {
pub visits: u32,
pub value: f64,
pub prior: f64,
}
impl NodeStats {
#[must_use]
pub fn mean_for(&self, side: Side) -> f64 {
if self.visits == 0 {
return 0.5;
}
let max = self.value / f64::from(self.visits);
match side {
Side::Max => max,
Side::Min => 1.0 - max,
}
}
}
pub trait Selection {
fn score(&self, side: Side, parent: &NodeStats, child: &NodeStats) -> f64;
fn unvisited_first(&self) -> bool {
true
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Uct {
pub exploration: f64,
}
impl Default for Uct {
fn default() -> Self {
Self {
exploration: core::f64::consts::SQRT_2,
}
}
}
impl Selection for Uct {
fn score(&self, side: Side, parent: &NodeStats, child: &NodeStats) -> f64 {
let parent = f64::from(parent.visits.max(1));
let visits = f64::from(child.visits.max(1));
child.mean_for(side) + self.exploration * libm::sqrt(libm::log(parent) / visits)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Puct {
pub c_puct: f64,
}
impl Default for Puct {
fn default() -> Self {
Self { c_puct: 1.25 }
}
}
impl Selection for Puct {
fn score(&self, side: Side, parent: &NodeStats, child: &NodeStats) -> f64 {
let parent = libm::sqrt(f64::from(parent.visits));
let exploration = child.prior * parent / (1.0 + f64::from(child.visits));
child.mean_for(side) + self.c_puct * exploration
}
fn unvisited_first(&self) -> bool {
false
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Evaluation {
pub value: f64,
}
impl Evaluation {
#[must_use]
pub const fn new(value: f64) -> Self {
Self { value }
}
}
pub trait Evaluator<G: Rewarded> {
fn evaluate<R: Random>(&mut self, game: &G, position: &G::Position, rng: &mut R) -> Evaluation;
fn priors(
&mut self,
game: &G,
position: &G::Position,
moves: &[G::Move],
priors: &mut Vec<f64>,
) {
let _ = (game, position, moves, priors);
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct BatchLeaf<'a, P, M> {
pub position: &'a P,
pub moves: &'a [M],
}
pub trait BatchEvaluator<G: Rewarded> {
fn evaluate_batch(
&mut self,
game: &G,
leaves: &[BatchLeaf<'_, G::Position, G::Move>],
values: &mut Vec<f64>,
priors: &mut Vec<f64>,
);
}
#[derive(Debug, Clone)]
pub struct Unbatched<E, R = super::random::SplitMix64> {
pub evaluator: E,
pub rng: R,
}
impl<E> Unbatched<E> {
#[must_use]
pub const fn new(evaluator: E, seed: u64) -> Self {
Self {
evaluator,
rng: super::random::SplitMix64::new(seed),
}
}
}
impl<G: Rewarded, E: Evaluator<G>, R: Random> BatchEvaluator<G> for Unbatched<E, R> {
fn evaluate_batch(
&mut self,
game: &G,
leaves: &[BatchLeaf<'_, G::Position, G::Move>],
values: &mut Vec<f64>,
priors: &mut Vec<f64>,
) {
for leaf in leaves {
values.push(
self.evaluator
.evaluate(game, leaf.position, &mut self.rng)
.value,
);
}
let mut own = Vec::new();
for leaf in leaves {
own.clear();
self.evaluator
.priors(game, leaf.position, leaf.moves, &mut own);
if own.len() != leaf.moves.len() {
priors.clear();
return;
}
priors.extend_from_slice(&own);
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rollout<M> {
pub max_plies: u32,
moves: Vec<M>,
}
impl<M> Rollout<M> {
#[must_use]
pub const fn new(max_plies: u32) -> Self {
Self {
max_plies,
moves: Vec::new(),
}
}
}
impl<M> Default for Rollout<M> {
fn default() -> Self {
Self::new(100)
}
}
impl<G: Rewarded> Evaluator<G> for Rollout<G::Move> {
fn evaluate<R: Random>(&mut self, game: &G, position: &G::Position, rng: &mut R) -> Evaluation {
let mut moves = core::mem::take(&mut self.moves);
let mut current = None;
for _ in 0..self.max_plies {
let here = current.as_ref().unwrap_or(position);
moves.clear();
game.moves(here, &mut moves);
if moves.is_empty() {
break;
}
let mv = &moves[rng.below(moves.len())];
current = Some(game.play(here, mv));
}
moves.clear();
self.moves = moves;
let leaf = current.as_ref().unwrap_or(position);
Evaluation::new(game.reward(game.evaluate(leaf)))
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct StaticValue;
impl<G: Rewarded> Evaluator<G> for StaticValue {
fn evaluate<R: Random>(&mut self, game: &G, position: &G::Position, _: &mut R) -> Evaluation {
Evaluation::new(game.reward(game.evaluate(position)))
}
}
#[cfg(test)]
mod tests {
use super::{NodeStats, Selection, Uct};
use crate::Side;
const fn stats(visits: u32, value: f64) -> NodeStats {
NodeStats {
visits,
value,
prior: 1.0,
}
}
#[test]
fn means_belong_to_the_side_to_move() {
assert!((stats(4, 3.0).mean_for(Side::Max) - 0.75).abs() < 1e-12);
assert!((stats(4, 3.0).mean_for(Side::Min) - 0.25).abs() < 1e-12);
assert!((stats(0, 0.0).mean_for(Side::Max) - 0.5).abs() < 1e-12);
}
#[test]
fn uct_explores_the_less_visited_child() {
let parent = stats(20, 10.0);
let uct = Uct::default();
let (rare, common) = (stats(2, 1.0), stats(18, 9.0));
assert!(uct.score(Side::Max, &parent, &rare) > uct.score(Side::Max, &parent, &common));
let greedy = Uct { exploration: 0.0 };
let gap =
greedy.score(Side::Max, &parent, &rare) - greedy.score(Side::Max, &parent, &common);
assert!(gap.abs() < 1e-12);
}
}