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>
469 lines
16 KiB
C++
469 lines
16 KiB
C++
#include "mcts.h"
|
|
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
#include <cstring>
|
|
#include <iostream>
|
|
#include <sstream>
|
|
|
|
#include "eval.h"
|
|
#include "uci_io.h"
|
|
|
|
namespace rigby {
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tree
|
|
// ---------------------------------------------------------------------------
|
|
|
|
void Tree::resize_mb(size_t mb) {
|
|
const size_t count = std::max<size_t>(mb * 1024 * 1024 / sizeof(Node), 1024);
|
|
nodes_.assign(count, Node{});
|
|
nodes_.shrink_to_fit();
|
|
clear();
|
|
}
|
|
|
|
void Tree::clear() {
|
|
used_ = 2; // index 0 is the null child, index 1 is the root
|
|
nodes_[root()] = Node{};
|
|
}
|
|
|
|
u32 Tree::alloc(u32 count) {
|
|
if (used_ + count > nodes_.size()) return 0;
|
|
const u32 idx = u32(used_);
|
|
used_ += count;
|
|
return idx;
|
|
}
|
|
|
|
size_t Tree::reroot(u32 new_root) {
|
|
if (new_root == root()) return used_;
|
|
|
|
// Every child block of the subtree, as (old first index, size).
|
|
std::vector<std::pair<u32, u32>> blocks;
|
|
std::vector<u32> stack{new_root};
|
|
while (!stack.empty()) {
|
|
const Node& node = nodes_[stack.back()];
|
|
stack.pop_back();
|
|
if (!node.first_child) continue;
|
|
blocks.emplace_back(node.first_child, node.num_children);
|
|
for (u32 i = 0; i < node.num_children; i++) stack.push_back(node.first_child + i);
|
|
}
|
|
|
|
// A block is always allocated after its parent's block, so packing the kept
|
|
// blocks in their original order only ever moves them towards the front, and
|
|
// never onto a block that has not moved yet. That allows doing it in place.
|
|
std::sort(blocks.begin(), blocks.end());
|
|
std::vector<u32> dest(blocks.size());
|
|
u32 next = 2;
|
|
for (size_t i = 0; i < blocks.size(); i++) {
|
|
dest[i] = next;
|
|
next += blocks[i].second;
|
|
}
|
|
|
|
const auto remap = [&](u32 old_first) -> u32 {
|
|
if (!old_first) return 0;
|
|
const auto it = std::lower_bound(blocks.begin(), blocks.end(), std::make_pair(old_first, u32(0)));
|
|
return dest[size_t(it - blocks.begin())];
|
|
};
|
|
|
|
// The new root's own slot may be overwritten by a moved block, so take it first.
|
|
Node new_root_node = nodes_[new_root];
|
|
new_root_node.first_child = remap(new_root_node.first_child);
|
|
|
|
for (size_t i = 0; i < blocks.size(); i++) {
|
|
const auto [first, count] = blocks[i];
|
|
if (dest[i] != first) std::memmove(&nodes_[dest[i]], &nodes_[first], size_t(count) * sizeof(Node));
|
|
for (u32 j = 0; j < count; j++) {
|
|
Node& node = nodes_[dest[i] + j];
|
|
node.first_child = remap(node.first_child);
|
|
}
|
|
}
|
|
|
|
nodes_[root()] = new_root_node;
|
|
used_ = next;
|
|
return used_ - 1; // everything but the null slot
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Searcher
|
|
// ---------------------------------------------------------------------------
|
|
|
|
Searcher::Searcher() { tree_.resize_mb(64); }
|
|
|
|
i64 Searcher::elapsed_ms() const {
|
|
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time_).count();
|
|
}
|
|
|
|
void Searcher::compute_time_limit(const SearchLimits& limits) {
|
|
time_limit_ms_ = 0;
|
|
if (limits.infinite) return;
|
|
|
|
if (limits.movetime) {
|
|
time_limit_ms_ = std::max<i64>(1, limits.movetime - params.move_overhead);
|
|
return;
|
|
}
|
|
|
|
const int us = root_pos_.stm;
|
|
if (limits.time[us] <= 0) return;
|
|
|
|
const i64 remaining = std::max<i64>(1, limits.time[us] - params.move_overhead);
|
|
const i64 moves_left = limits.movestogo ? std::min(limits.movestogo, 40) : 25;
|
|
const i64 target = remaining / moves_left + limits.inc[us] * 3 / 4;
|
|
time_limit_ms_ = std::clamp<i64>(target, 1, remaining / 2 + 1);
|
|
}
|
|
|
|
bool Searcher::should_stop(const SearchLimits& limits) const {
|
|
if (stop_flag.load(std::memory_order_relaxed)) return true;
|
|
if (limits.nodes && iterations_ >= limits.nodes) return true;
|
|
if (limits.depth && iterations_) {
|
|
// "depth" is the mean playout depth. Solved positions may never get
|
|
// there, so a depth limit also carries a generous playout cap.
|
|
if (int(depth_sum_ / iterations_) >= limits.depth) return true;
|
|
if (iterations_ >= (u64(1000) << std::min(2 * limits.depth, 14))) return true;
|
|
}
|
|
// The clock is cheap but not free; look at it every 64 playouts.
|
|
if (time_limit_ms_ && (iterations_ & 63) == 0 && elapsed_ms() >= time_limit_ms_) return true;
|
|
return false;
|
|
}
|
|
|
|
bool Searcher::is_repetition(const Position& pos) const {
|
|
// history_.back() is the key of `pos` itself. Any earlier occurrence with the
|
|
// same side to move inside the reversible window counts as a draw (two-fold).
|
|
const int n = int(history_.size());
|
|
for (int back = 4; back <= pos.halfmove && back < n; back += 2)
|
|
if (history_[n - 1 - back] == pos.key) return true;
|
|
return false;
|
|
}
|
|
|
|
size_t Searcher::reuse_tree(const Position& root) {
|
|
// The new game history must continue the previous one; the keys after the
|
|
// old root are the positions reached by the moves played since.
|
|
if (!tree_valid_ || history_.size() < prev_history_.size() ||
|
|
!std::equal(prev_history_.begin(), prev_history_.end(), history_.begin()))
|
|
return 0;
|
|
|
|
u32 idx = Tree::root();
|
|
Position pos = prev_root_;
|
|
for (size_t i = prev_history_.size(); i < history_.size(); i++) {
|
|
const Node& node = tree_[idx];
|
|
if (node.state != EXPANDED) return 0;
|
|
|
|
u32 next = 0;
|
|
for (u32 c = 0; c < node.num_children && !next; c++) {
|
|
Position child = pos;
|
|
child.make_move(Move::from_raw(tree_[node.first_child + c].move));
|
|
if (child.key == history_[i]) {
|
|
next = node.first_child + c;
|
|
pos = child;
|
|
}
|
|
}
|
|
if (!next) return 0;
|
|
idx = next;
|
|
}
|
|
|
|
// A node that was a draw by repetition or the 50-move rule inside the old
|
|
// tree can be a real position to play from now; start such a root afresh.
|
|
if (pos.key != root.key || tree_[idx].state != EXPANDED) return 0;
|
|
|
|
return tree_.reroot(idx);
|
|
}
|
|
|
|
#ifdef RIGBY_VERIFY_TREE
|
|
// Debug check: the tree must still describe legal play from the root, and every
|
|
// expanded node must have at least one visit more than its children together
|
|
// (more when it was evaluated as a leaf while the tree was full).
|
|
void Searcher::verify_tree() const {
|
|
struct Item {
|
|
u32 idx;
|
|
Position pos;
|
|
};
|
|
std::vector<Item> stack{{Tree::root(), root_pos_}};
|
|
u64 checked = 0;
|
|
while (!stack.empty()) {
|
|
const Item item = stack.back();
|
|
stack.pop_back();
|
|
const Node& node = tree_[item.idx];
|
|
checked++;
|
|
if (node.state != EXPANDED) continue;
|
|
|
|
MoveList legal;
|
|
generate_legal(item.pos, legal);
|
|
u64 child_visits = 0;
|
|
bool ok = node.first_child >= 2 && node.first_child + node.num_children <= tree_.used() &&
|
|
node.num_children == legal.size();
|
|
for (u32 c = 0; ok && c < node.num_children; c++) {
|
|
const Node& child = tree_[node.first_child + c];
|
|
const Move m = Move::from_raw(child.move);
|
|
ok = std::find(legal.begin(), legal.end(), m) != legal.end();
|
|
child_visits += child.visits;
|
|
Position next = item.pos;
|
|
next.make_move(m);
|
|
stack.push_back({node.first_child + c, next});
|
|
}
|
|
// The root is expanded before its first visit, so it may have exactly
|
|
// as many visits as its children.
|
|
const u64 own_visit = item.idx == Tree::root() ? 0 : 1;
|
|
if (!ok || node.visits < child_visits + own_visit) {
|
|
std::cerr << "TREE CORRUPT at node " << item.idx << " (" << item.pos.fen() << ") ok=" << ok
|
|
<< " visits=" << node.visits << " child_visits=" << child_visits
|
|
<< " children=" << int(node.num_children) << " legal=" << legal.size()
|
|
<< " first=" << node.first_child << " used=" << tree_.used() << std::endl;
|
|
std::abort();
|
|
}
|
|
}
|
|
uci_io::send("info string tree verified: " + std::to_string(checked) + " nodes");
|
|
}
|
|
#endif
|
|
|
|
float Searcher::evaluate_leaf(u32 idx, const Position& pos, int depth) {
|
|
Node& node = tree_[idx];
|
|
|
|
MoveList moves;
|
|
generate_legal(pos, moves);
|
|
|
|
if (moves.empty()) {
|
|
node.state = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
|
|
return node.state == TERMINAL_LOSS ? -1.0f : 0.0f;
|
|
}
|
|
|
|
// The root must always produce a move, so it is never declared drawn.
|
|
if (depth > 0 && (pos.halfmove >= 100 || pos.insufficient_material() || is_repetition(pos))) {
|
|
node.state = TERMINAL_DRAW;
|
|
return 0.0f;
|
|
}
|
|
|
|
return eval::value(pos);
|
|
}
|
|
|
|
bool Searcher::expand(u32 idx, const Position& pos) {
|
|
Node& node = tree_[idx];
|
|
|
|
MoveList moves;
|
|
generate_legal(pos, moves);
|
|
|
|
const u32 first = tree_.alloc(u32(moves.size()));
|
|
if (!first) {
|
|
// Out of memory: the node stays a leaf and is evaluated again.
|
|
tree_full_ = true;
|
|
return false;
|
|
}
|
|
|
|
float priors[256];
|
|
eval::policy(pos, moves, params.policy_temperature, priors);
|
|
|
|
for (int i = 0; i < moves.size(); i++) {
|
|
Node& child = tree_[first + i];
|
|
child = Node{};
|
|
child.move = moves[i].raw();
|
|
child.policy = u16(std::lround(std::clamp(priors[i], 0.0f, 1.0f) * 65535.0f));
|
|
}
|
|
|
|
node.first_child = first;
|
|
node.num_children = u8(moves.size());
|
|
node.state = EXPANDED;
|
|
return true;
|
|
}
|
|
|
|
u32 Searcher::select_child(u32 idx) const {
|
|
const Node& node = tree_[idx];
|
|
|
|
// node.q is from the view of the side that moved into this node, so the side
|
|
// to move here sees -q.
|
|
const float parent_q = node.visits ? -node.q : 0.0f;
|
|
|
|
float visited_policy = 0.0f;
|
|
for (u32 i = 0; i < node.num_children; i++) {
|
|
const Node& child = tree_[node.first_child + i];
|
|
if (child.visits) visited_policy += child.prior();
|
|
}
|
|
|
|
const float fpu = parent_q - params.fpu_reduction * std::sqrt(visited_policy);
|
|
const float explore = params.cpuct * std::sqrt(float(std::max<u32>(node.visits, 1)));
|
|
|
|
u32 best = node.first_child;
|
|
float best_score = -1e30f;
|
|
for (u32 i = 0; i < node.num_children; i++) {
|
|
const u32 c = node.first_child + i;
|
|
const Node& child = tree_[c];
|
|
const float q = child.visits ? child.q : fpu;
|
|
const float score = q + explore * child.prior() / float(1 + child.visits);
|
|
if (score > best_score) {
|
|
best_score = score;
|
|
best = c;
|
|
}
|
|
}
|
|
return best;
|
|
}
|
|
|
|
void Searcher::playout() {
|
|
Position pos = root_pos_;
|
|
history_.resize(root_history_size_);
|
|
path_.clear();
|
|
|
|
u32 idx = Tree::root();
|
|
path_.push_back(idx);
|
|
int depth = 0;
|
|
float value;
|
|
|
|
for (;;) {
|
|
const Node& node = tree_[idx];
|
|
if (node.state == TERMINAL_LOSS) {
|
|
value = -1.0f;
|
|
break;
|
|
}
|
|
if (node.state == TERMINAL_DRAW) {
|
|
value = 0.0f;
|
|
break;
|
|
}
|
|
if (node.state == UNEXPANDED) {
|
|
// Most leaves are only ever visited once, so a first visit just
|
|
// evaluates; children (moves, priors, memory) come on the second.
|
|
if (node.visits == 0) {
|
|
value = evaluate_leaf(idx, pos, depth);
|
|
break;
|
|
}
|
|
if (!expand(idx, pos)) {
|
|
value = eval::value(pos);
|
|
break;
|
|
}
|
|
}
|
|
|
|
idx = select_child(idx);
|
|
pos.make_move(Move::from_raw(tree_[idx].move));
|
|
history_.push_back(pos.key);
|
|
path_.push_back(idx);
|
|
depth++;
|
|
}
|
|
|
|
// `value` is from the view of the side to move at the leaf. Each node stores
|
|
// the view of the side that moved into it, so flip before every update.
|
|
for (size_t i = path_.size(); i-- > 0;) {
|
|
value = -value;
|
|
Node& node = tree_[path_[i]];
|
|
node.visits++;
|
|
node.q += (value - node.q) / float(node.visits);
|
|
}
|
|
|
|
iterations_++;
|
|
depth_sum_ += u64(depth);
|
|
seldepth_ = std::max(seldepth_, depth);
|
|
}
|
|
|
|
u32 Searcher::best_child(u32 idx) const {
|
|
const Node& node = tree_[idx];
|
|
u32 best = 0;
|
|
for (u32 i = 0; i < node.num_children; i++) {
|
|
const u32 c = node.first_child + i;
|
|
if (!best) {
|
|
best = c;
|
|
continue;
|
|
}
|
|
const Node& a = tree_[c];
|
|
const Node& b = tree_[best];
|
|
// Most visits wins; ties go to the better Q, then to the higher prior.
|
|
if (a.visits != b.visits ? a.visits > b.visits : a.visits ? a.q > b.q : a.policy > b.policy) best = c;
|
|
}
|
|
return best;
|
|
}
|
|
|
|
void Searcher::print_info() const {
|
|
const Node& root = tree_[Tree::root()];
|
|
const i64 ms = elapsed_ms();
|
|
const u32 best = best_child(Tree::root());
|
|
|
|
std::ostringstream out;
|
|
out << "info depth " << (iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0) << " seldepth "
|
|
<< seldepth_;
|
|
|
|
const float q = best && tree_[best].visits ? tree_[best].q : -root.q;
|
|
out << " score cp " << eval::q_to_cp(q);
|
|
out << " nodes " << iterations_ << " nps " << (ms ? iterations_ * 1000 / u64(ms) : iterations_) << " time " << ms;
|
|
out << " hashfull " << (tree_.used() * 1000 / tree_.capacity());
|
|
|
|
out << " pv";
|
|
u32 idx = Tree::root();
|
|
for (int ply = 0; ply < 64; ply++) {
|
|
const u32 c = best_child(idx);
|
|
if (!c || !tree_[c].visits) break;
|
|
out << ' ' << Move::from_raw(tree_[c].move).to_uci();
|
|
idx = c;
|
|
}
|
|
uci_io::send(out.str());
|
|
}
|
|
|
|
SearchResult Searcher::search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
|
|
bool print) {
|
|
start_time_ = Clock::now();
|
|
root_pos_ = root;
|
|
history_ = history;
|
|
if (history_.empty() || history_.back() != root.key) history_.push_back(root.key);
|
|
root_history_size_ = history_.size();
|
|
|
|
#ifdef RIGBY_VERIFY_TREE
|
|
// Check the previous tree as the last search left it, and again after rerooting.
|
|
if (tree_valid_ && history_.size() >= prev_history_.size()) {
|
|
root_pos_ = prev_root_;
|
|
verify_tree();
|
|
root_pos_ = root;
|
|
}
|
|
#endif
|
|
const size_t reused = reuse_tree(root);
|
|
if (!reused) tree_.clear();
|
|
#ifdef RIGBY_VERIFY_TREE
|
|
if (reused) verify_tree();
|
|
#endif
|
|
if (print && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes");
|
|
iterations_ = 0;
|
|
depth_sum_ = 0;
|
|
seldepth_ = 0;
|
|
tree_full_ = false;
|
|
compute_time_limit(limits);
|
|
|
|
SearchResult result;
|
|
|
|
MoveList root_moves;
|
|
generate_legal(root, root_moves);
|
|
if (root_moves.empty()) {
|
|
tree_valid_ = false;
|
|
if (print) uci_io::send("info depth 0 score " + std::string(root.in_check() ? "mate 0" : "cp 0"));
|
|
return result;
|
|
}
|
|
|
|
// The root needs its children before the first playout, so that even a
|
|
// single playout leaves a move to play.
|
|
if (tree_[Tree::root()].state == UNEXPANDED && !expand(Tree::root(), root)) {
|
|
tree_.clear();
|
|
tree_full_ = false;
|
|
expand(Tree::root(), root);
|
|
}
|
|
|
|
i64 last_info = 0;
|
|
do {
|
|
playout();
|
|
if (print && (iterations_ & 1023) == 0) {
|
|
const i64 ms = elapsed_ms();
|
|
if (ms - last_info >= 1000) {
|
|
last_info = ms;
|
|
print_info();
|
|
}
|
|
}
|
|
} while (!should_stop(limits));
|
|
|
|
if (print) {
|
|
print_info();
|
|
if (tree_full_) uci_io::send("info string tree memory full, raise Hash");
|
|
}
|
|
|
|
const u32 best = best_child(Tree::root());
|
|
result.best = Move::from_raw(tree_[best].move);
|
|
result.nodes = iterations_;
|
|
result.tree_positions = iterations_ + depth_sum_;
|
|
result.time_ms = elapsed_ms();
|
|
|
|
tree_valid_ = true;
|
|
prev_root_ = root;
|
|
prev_history_.assign(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_));
|
|
return result;
|
|
}
|
|
|
|
} // namespace rigby
|