Files
Rigby/src/mcts.h
T
rektdieandclaude cdeb318016 feat: expand nodes on their second visit
Most leaves are visited only once. Their first visit now only settles
terminal states and evaluates the position; the move list, the priors
and the child nodes are created when search comes back a second time.
The root is expanded before the first playout, so a search always has a
move.

With the value network the tree is full on nearly every move at
8+0.08 with Hash=64 (hashfull 1000 in a 30-ply self-play diagnostic);
with this change many moves stay at 320-890. The -DRIGBY_VERIFY_TREE
build passed 1700 tree checks in UCI-driven self-play with 1 MB and
16 MB Hash, and a 1-playout search still returns a move.

Rebased from the earlier expand-second-visit branch onto the network
main, without the tree collection it was built on.

Bench: 546018

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

143 lines
3.9 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();
// First visit of a node: settles terminal states, otherwise evaluates.
float evaluate_leaf(u32 idx, const Position& pos, int depth);
// Second visit: creates the children with their priors. False when the
// arena is full (a collection is then scheduled).
bool expand(u32 idx, const Position& pos);
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