Files
Rigby/src/mcts.h
T
rektdieandclaude 5c017ee43f feat: reuse the search tree between moves
When the new position continues the previous game, find its node in the
old tree (matching the keys of the positions played since) and make it
the root. Its subtree is packed to the front of the arena in place: child
blocks are always allocated after their parent's, so moving the kept
blocks in their original order only moves them towards the front.

A root that was a draw inside the old tree (repetition, 50 moves) or was
never expanded starts afresh. ucinewgame and Hash changes drop the tree.

Built with -DRIGBY_VERIFY_TREE, the engine checks every tree before and
after reuse (legal moves, visit counts); 2900+ such checks over self-play
games, with 16 MB and 1 MB hash, found no inconsistency.

Bench: 546127

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:23:42 +01:00

139 lines
3.6 KiB
C++

#pragma once
#include <atomic>
#include <chrono>
#include <vector>
#include "position.h"
namespace rigby {
enum NodeState : u8 {
UNEXPANDED = 0,
EXPANDED,
TERMINAL_LOSS, // side to move is checkmated
TERMINAL_DRAW,
};
// 20 bytes. Children of a node sit next to each other in the arena, so a node
// only needs the index of its first child.
struct Node {
u32 first_child = 0;
u32 visits = 0;
float q = 0.0f; // running mean, from the view of the side that played `move`
u16 move = 0;
u16 policy = 0; // prior scaled to 0..65535
u8 num_children = 0;
u8 state = UNEXPANDED;
float prior() const { return float(policy) * (1.0f / 65535.0f); }
};
class Tree {
public:
void resize_mb(size_t mb);
void clear();
// Returns the index of `count` fresh nodes, or 0 when the arena is full.
u32 alloc(u32 count);
// Makes `new_root` the root and packs its subtree to the front of the arena;
// everything else is dropped. Returns the number of nodes kept.
size_t reroot(u32 new_root);
Node& operator[](u32 idx) { return nodes_[idx]; }
const Node& operator[](u32 idx) const { return nodes_[idx]; }
static constexpr u32 root() { return 1; }
size_t used() const { return used_; }
size_t capacity() const { return nodes_.size(); }
private:
std::vector<Node> nodes_;
size_t used_ = 0;
};
struct SearchLimits {
u64 nodes = 0;
i64 movetime = 0;
i64 time[2] = {0, 0};
i64 inc[2] = {0, 0};
int movestogo = 0;
int depth = 0;
bool infinite = false;
};
struct SearchParams {
float cpuct = 1.60f;
float fpu_reduction = 0.30f;
float policy_temperature = 1.00f;
i64 move_overhead = 20;
};
struct SearchResult {
Move best;
u64 nodes = 0; // playouts
u64 tree_positions = 0; // positions visited across all playouts (bench signature)
i64 time_ms = 0;
};
class Searcher {
public:
SearchParams params;
std::atomic<bool> stop_flag{false};
Searcher();
void set_hash(size_t mb) {
tree_.resize_mb(mb);
tree_valid_ = false;
}
// Forget the previous tree, e.g. on ucinewgame.
void new_game() { tree_valid_ = false; }
// Synchronous search. `history` holds the keys of every position that led to
// `root`, including the key of `root` itself (for repetition detection).
SearchResult search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
bool print_info);
private:
using Clock = std::chrono::steady_clock;
Tree tree_;
Position root_pos_;
std::vector<u64> history_;
size_t root_history_size_ = 0;
std::vector<u32> path_;
// The previous search, kept so its tree can be reused.
bool tree_valid_ = false;
Position prev_root_;
std::vector<u64> prev_history_;
Clock::time_point start_time_;
i64 time_limit_ms_ = 0;
u64 iterations_ = 0;
u64 depth_sum_ = 0;
int seldepth_ = 0;
bool tree_full_ = false;
void playout();
float expand(u32 idx, const Position& pos, int depth);
u32 select_child(u32 idx) const;
bool is_repetition(const Position& pos) const;
// Finds the node for `root` in the previous tree and makes it the root.
// Returns the number of nodes kept, 0 when nothing could be reused.
size_t reuse_tree(const Position& root);
#ifdef RIGBY_VERIFY_TREE
void verify_tree() const;
#endif
void compute_time_limit(const SearchLimits& limits);
i64 elapsed_ms() const;
bool should_stop(const SearchLimits& limits) const;
u32 best_child(u32 idx) const;
void print_info() const;
};
} // namespace rigby