Files
Rigby/src/mcts.cpp
T
rektdieandclaude 19aedfdce9 Merge main into mcgs-v-novaluehash
Brings in the stop rule (PR #24). The combined code passed the gates:
zero warnings, verify (a)-(d), VERIFY searches with forced GC, reuse at
Hash 64, Hash 1 and 960, smoke positions.

Bench: 608763

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

1231 lines
51 KiB
C++

#include "mcts.h"
#include <algorithm>
#include <bit>
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <random>
#include <sstream>
#include <tuple>
#include "eval.h"
#include "pretty.h"
#include "uci_io.h"
namespace rigby {
// ---------------------------------------------------------------------------
// Tree
// ---------------------------------------------------------------------------
u16 position_check(const Position& pos) {
u64 x = pos.colors[WHITE] ^ std::rotl(pos.pieces[PAWN], 17) ^ std::rotl(pos.pieces[KING], 41);
// splitmix64's finaliser
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
return u16(x ^ (x >> 31));
}
void Tree::resize_bytes(size_t bytes) {
// A node costs its own 32 bytes, EDGES_PER_NODE edges of 16 and at least
// two table slots of 8. The table's size is a power of two of at least
// twice the nodes; of rounding its slots down or up, take the one that
// leaves room for more nodes within `bytes`.
const size_t arena_per_node = sizeof(Node) + EDGES_PER_NODE * sizeof(Edge);
const size_t want = std::max<size_t>(bytes / (arena_per_node + 2 * sizeof(Slot)), 1024);
size_t node_count = 0, slots = 0;
for (const size_t s : {std::bit_floor(2 * want), std::bit_ceil(2 * want)}) {
const size_t table_bytes = s * sizeof(Slot);
if (table_bytes >= bytes) continue;
const size_t n = std::min(s / 2, (bytes - table_bytes) / arena_per_node);
if (n > node_count) {
node_count = n;
slots = s;
}
}
if (node_count < 1024) {
node_count = 1024;
slots = 2048;
}
nodes_.assign(node_count, Node{});
nodes_.shrink_to_fit();
edges_.assign(node_count * EDGES_PER_NODE, Edge{});
edges_.shrink_to_fit();
table_.assign(slots, Slot{});
table_.shrink_to_fit();
table_mask_ = slots - 1;
clear();
}
void Tree::clear() {
nodes_used_ = 1; // index 0 is the null node
edges_used_ = 1; // index 0 is the null edge
root_ = 0;
std::fill(table_.begin(), table_.end(), Slot{});
table_entries_ = 0;
}
u32 Tree::find(u64 key, u16 check) const {
const u32 hi = u32(key >> 32);
for (size_t i = size_t(key) & table_mask_;; i = (i + 1) & table_mask_) {
const Slot& s = table_[i];
if (!s.node) return 0;
if (s.key_hi == hi) {
const Node& n = nodes_[s.node];
if (n.key == key && n.check == check) return s.node;
}
}
}
void Tree::insert(u32 idx) {
const u64 key = nodes_[idx].key;
size_t i = size_t(key) & table_mask_;
while (table_[i].node) i = (i + 1) & table_mask_;
table_[i] = Slot{u32(key >> 32), idx};
table_entries_++;
}
void Tree::rebuild_table() {
std::fill(table_.begin(), table_.end(), Slot{});
table_entries_ = 0;
for (u32 i = 1; i < nodes_used_; i++) insert(i);
}
u32 Tree::alloc_node() {
if (nodes_used_ >= nodes_.size()) return 0;
return u32(nodes_used_++);
}
u32 Tree::alloc_edges(u32 count) {
if (edges_used_ + count > edges_.size()) return 0;
const u32 idx = u32(edges_used_);
edges_used_ += count;
return idx;
}
size_t Tree::reroot(u32 new_root) {
// Only the root moves. Packing what stays reachable would cost O(graph) on
// every move, because in a reversible endgame almost the whole graph stays
// reachable from the new root. Nodes that are no longer reachable keep
// their memory and their table entries (search may link to them again)
// until the next collection, which keeps only what the root reaches.
root_ = new_root;
return nodes_used_ - 1;
}
size_t Tree::collect_garbage(double keep_fraction) {
return collect_garbage(size_t(double(nodes_.size()) * keep_fraction), size_t(double(edges_.size()) * keep_fraction));
}
size_t Tree::collect_garbage(size_t node_target, size_t edge_target) {
return compact(root_, prune_threshold(node_target, edge_target));
}
u32 Tree::prune_threshold(size_t node_target, size_t edge_target) const {
// A node keeps its edges through a collection with threshold T when it is
// still reachable and has at least T visits, and the child nodes of those
// edges stay. The estimate for T counts the edges and edge targets of
// every reachable node with at least T visits, plus the root's, which
// always stay. In a tree, where visits only shrink going down, that is
// exactly what is kept. In a graph it can only be more (a node reachable
// only through pruned nodes goes, and a shared child is counted once per
// edge), so what is kept stays within the targets.
constexpr u32 CAP = 1 << 16;
std::vector<u64> edges_by_visits(CAP + 1, 0);
std::vector<u64> children_by_visits(CAP + 1, 0);
std::vector<u8> seen(nodes_used_, 0);
std::vector<u32> stack{root_};
seen[root_] = 1;
u64 kept_nodes = 2; // null node and root
u64 kept_edges = 1; // null edge
while (!stack.empty()) {
const u32 idx = stack.back();
const Node& node = nodes_[idx];
stack.pop_back();
if (!node.first_edge) continue;
const u32 bucket = std::min(node.visits, CAP);
u64 children = 0;
for (u32 i = 0; i < node.num_edges; i++) {
const u32 child = edges_[node.first_edge + i].child;
if (!child) continue;
children++;
if (!seen[child]) {
seen[child] = 1;
stack.push_back(child);
}
}
if (idx == root_) {
kept_nodes += children;
kept_edges += node.num_edges;
} else {
children_by_visits[bucket] += children;
edges_by_visits[bucket] += node.num_edges;
}
}
for (u32 v = CAP; v >= 1; v--) {
if (kept_nodes + children_by_visits[v] > node_target || kept_edges + edges_by_visits[v] > edge_target)
return v + 1;
kept_nodes += children_by_visits[v];
kept_edges += edges_by_visits[v];
}
return 1;
}
size_t Tree::compact(u32 new_root, u32 min_visits) {
// Mark: everything reachable from the new root stays. A node below the
// visit threshold loses its edges and becomes a leaf again; it keeps its
// visits and Q, as its own value u with weight base, and gets expanded
// anew if search comes back to it. Each node is marked once, however many
// edges lead to it. `blocks` collects every edge block that stays, as
// (old first index, size).
std::vector<u8> marked(nodes_used_, 0);
std::vector<std::pair<u32, u32>> blocks;
std::vector<u32> stack{new_root};
marked[new_root] = 1;
while (!stack.empty()) {
const u32 idx = stack.back();
stack.pop_back();
Node& node = nodes_[idx];
if (!node.first_edge) continue;
if (idx != new_root && node.visits < min_visits) {
node.first_edge = 0;
node.num_edges = 0;
node.state = UNEXPANDED;
node.u = node.q;
node.base = node.visits;
continue;
}
blocks.emplace_back(node.first_edge, node.num_edges);
for (u32 i = 0; i < node.num_edges; i++) {
const u32 child = edges_[node.first_edge + i].child;
if (child && !marked[child]) {
marked[child] = 1;
stack.push_back(child);
}
}
}
// Forwarding: the marked nodes and the kept edge blocks get new places in
// their old index order. Every destination is then at or before its
// source, so both arenas can slide to the front in place, whatever order
// things were allocated in.
std::vector<u32> forward(nodes_used_, 0);
u32 next_node = 1;
for (u32 i = 1; i < nodes_used_; i++)
if (marked[i]) forward[i] = next_node++;
std::sort(blocks.begin(), blocks.end());
std::vector<u32> dest(blocks.size());
u32 next_edge = 1;
for (size_t i = 0; i < blocks.size(); i++) {
dest[i] = next_edge;
next_edge += blocks[i].second;
}
const auto remap_edges = [&](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())];
};
for (u32 i = 1; i < nodes_used_; i++) {
if (!marked[i]) continue;
Node& node = nodes_[forward[i]];
if (forward[i] != i) node = nodes_[i];
node.first_edge = remap_edges(node.first_edge);
}
for (size_t i = 0; i < blocks.size(); i++) {
const auto [first, count] = blocks[i];
if (dest[i] != first) std::memmove(&edges_[dest[i]], &edges_[first], size_t(count) * sizeof(Edge));
for (u32 j = 0; j < count; j++) {
Edge& e = edges_[dest[i] + j];
e.child = forward[e.child];
}
}
root_ = forward[new_root];
nodes_used_ = next_node;
edges_used_ = next_edge;
// Node indices moved, so the table starts over from the survivors' keys.
rebuild_table();
return nodes_used_ - 1; // everything but the null node
}
// ---------------------------------------------------------------------------
// Searcher
// ---------------------------------------------------------------------------
Searcher::Searcher() { set_hash(64); }
void Searcher::clear_tree(const Position& root) {
// The root is created like any node and evaluated once; its own value
// takes part in its Q with weight 1, as at every other node.
tree_.clear();
float value;
tree_.set_root(create_node(root, true, value));
}
bool Searcher::root_edges_valid(const Position& root) const {
const Node& node = tree_.node(tree_.root());
if (node.key != root.key || node.check != position_check(root)) return false;
if (node.state != EXPANDED) return node.state == UNEXPANDED;
MoveList legal;
generate_legal(root, legal);
if (node.num_edges != legal.size()) return false;
bool seen[256] = {};
for (u32 i = 0; i < node.num_edges; i++) {
const auto it = std::find(legal.begin(), legal.end(), Move::from_raw(tree_.edge(node.first_edge + i).move));
if (it == legal.end() || seen[it - legal.begin()]) return false;
seen[it - legal.begin()] = true;
}
return true;
}
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;
hard_limit_ms_ = 0;
clock_search_ = false;
if (limits.infinite) return;
if (limits.movetime) {
time_limit_ms_ = hard_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);
// A move that is still open at the soft limit may run on up to this.
hard_limit_ms_ = std::max(time_limit_ms_, std::min(time_limit_ms_ * HARD_LIMIT_FACTOR, remaining / 3));
clock_search_ = true;
}
bool Searcher::best_move_settled(i64 ms, i64 limit_ms) const {
// Smart pruning (Lc0): stop when no other root move can catch up with the
// leading one in the playouts the remaining time still allows, at the
// speed so far, scaled down by SMART_PRUNING_FACTOR. Only the visits of
// this search count: a reused tree often brings the best move so many
// visits that nothing could overtake it, which would stop every search
// at once. The move leading this search must also be the one played.
if (ms <= 0 || iterations_ < 256) return false;
const Node& root = tree_.node(tree_.root());
if (root_start_visits_.size() != root.num_edges) return false;
u32 first = 0, second = 0, leader = 0;
for (u32 i = 0; i < root.num_edges; i++) {
const u32 v = tree_.edge(root.first_edge + i).visits - root_start_visits_[i];
if (v > first) {
second = first;
first = v;
leader = root.first_edge + i;
} else if (v > second) {
second = v;
}
}
if (leader != best_edge(tree_.root())) return false;
const double remaining =
double(iterations_) / double(ms) * double(limit_ms - ms) / SMART_PRUNING_FACTOR;
return double(second) + remaining < double(first);
}
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) {
const i64 ms = elapsed_ms();
if (ms >= hard_limit_ms_) return true;
// Under a game clock the time saved on a settled move goes to later
// moves. A move that is not settled by the soft limit (time_limit_ms_)
// is an open one: it searches on until it settles against the hard
// limit or reaches it. Other limits stop at the soft limit, which is
// also their hard one.
const bool extended = ms >= time_limit_ms_;
if (clock_search_ && best_move_settled(ms, extended ? hard_limit_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_.node(idx);
if (node.state != EXPANDED) return 0;
u32 next = 0;
for (u32 c = 0; c < node.num_edges && !next; c++) {
const Edge& e = tree_.edge(node.first_edge + c);
Position child = pos;
child.make_move(Move::from_raw(e.move));
if (child.key == history_[i]) {
// A move search never tried has no node to continue from.
if (!e.child) return 0;
next = e.child;
pos = child;
}
}
if (!next) return 0;
idx = next;
}
// A terminal node can still be a position to play from (insufficient
// material is never terminal at the root); start such a root afresh.
if (pos.key != root.key || tree_.node(idx).state != EXPANDED) return 0;
return tree_.reroot(idx);
}
#ifdef RIGBY_VERIFY_TREE
// Debug check of the graph from the root as `root_pos_`, with the game
// history `history` (ending with the root's key). Each node is checked once,
// with the position of the first path that reaches it (positions do not
// depend on the path, apart from the clocks):
// - right after a collection every node is reachable, and the arenas hold
// nothing else; at other times a reroot may have left nodes the root no
// longer reaches (they wait for the next collection);
// - a node's key and check match its position, and the table finds it there;
// the table has one entry per node in the arena, reachable or not, and
// nothing else;
// - its state is what the position itself decides: checkmate, stalemate or
// insufficient material (not at the root, nor at an earlier root, i.e. a
// position of the game history). Repetitions and the 50-move rule never
// show in a node;
// - an expanded node has one edge per legal move;
// - an edge has no more draws than visits, and a child node whenever it has
// a visit that was not a draw;
// - N = base + the edges' visits; a node without edges has q = u;
// - Q and u are finite and in [-1, 1].
void Searcher::verify_tree(const std::vector<u64>& history, bool collected) const {
const auto fail = [&](u32 idx, const Position& pos, const std::string& what) {
const Node& n = tree_.node(idx);
std::cerr << "GRAPH CORRUPT at node " << idx << " (" << pos.fen() << "): " << what << " visits=" << n.visits
<< " base=" << n.base << " q=" << n.q << " u=" << n.u << " state=" << int(n.state)
<< " edges=" << int(n.num_edges) << " first=" << n.first_edge << " nodes_used=" << tree_.nodes_used()
<< " edges_used=" << tree_.edges_used() << " table=" << tree_.table_entries() << std::endl;
std::abort();
};
const u32 root = tree_.root();
if (root == 0 || root >= tree_.nodes_used()) fail(root, root_pos_, "bad root index");
std::vector<u8> seen(tree_.nodes_used(), 0);
std::vector<std::pair<u32, Position>> stack{{root, root_pos_}};
seen[root] = 1;
u64 nodes = 0, edges = 0;
while (!stack.empty()) {
const auto [idx, pos] = stack.back();
stack.pop_back();
const Node& node = tree_.node(idx);
nodes++;
if (node.key != pos.key || node.check != position_check(pos)) fail(idx, pos, "key or check mismatch");
if (tree_.find(pos.key, position_check(pos)) != idx) fail(idx, pos, "the table does not find the node");
if (!std::isfinite(node.q) || std::abs(node.q) > 1.0f || !std::isfinite(node.u) || std::abs(node.u) > 1.0f)
fail(idx, pos, "q or u out of range");
if (!node.visits || node.visits < node.base) fail(idx, pos, "visits below base");
MoveList legal;
generate_legal(pos, legal);
// A position of the game was a root (never drawn by insufficient
// material) and may have been created as a non-root before, so
// either state is fine there; the current root is never terminal.
const bool in_history = std::find(history.begin(), history.end(), pos.key) != history.end();
int expected = -1; // not terminal
if (legal.empty()) expected = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
else if (pos.insufficient_material() && idx != root && !in_history) expected = TERMINAL_DRAW;
const bool ok = expected >= 0 ? node.state == expected
: node.state == UNEXPANDED || node.state == EXPANDED ||
(node.state == TERMINAL_DRAW && idx != root && in_history &&
pos.insufficient_material());
if (!ok) fail(idx, pos, "state " + std::to_string(node.state) + " expected " + std::to_string(expected));
if (node.state != EXPANDED) {
if (node.first_edge || node.num_edges) fail(idx, pos, "edges on a node that is not expanded");
if (node.visits != node.base || node.q != node.u) fail(idx, pos, "leaf with visits != base or q != u");
continue;
}
if (!node.first_edge || node.first_edge + node.num_edges > tree_.edges_used() ||
node.num_edges != legal.size())
fail(idx, pos, "bad edge block, legal moves " + std::to_string(legal.size()));
bool legal_seen[256] = {};
u64 edge_visits = 0;
for (u32 i = 0; i < node.num_edges; i++) {
const Edge& e = tree_.edge(node.first_edge + i);
const auto it = std::find(legal.begin(), legal.end(), Move::from_raw(e.move));
if (it == legal.end() || legal_seen[it - legal.begin()]) fail(idx, pos, "illegal or repeated edge move");
legal_seen[it - legal.begin()] = true;
if (e.draws > e.visits) fail(idx, pos, "edge with more draws than visits");
if (e.child >= tree_.nodes_used()) fail(idx, pos, "edge child out of range");
if (e.visits > e.draws && !e.child) fail(idx, pos, "edge with non-draw visits and no child");
edge_visits += e.visits;
if (e.child && !seen[e.child]) {
seen[e.child] = 1;
Position next = pos;
next.make_move(Move::from_raw(e.move));
stack.push_back({e.child, next});
}
}
edges += node.num_edges;
if (node.visits != node.base + edge_visits)
fail(idx, pos, "visits != base + edge visits " + std::to_string(edge_visits));
}
const u64 all_nodes = tree_.nodes_used() - 1, all_edges = tree_.edges_used() - 1;
if (collected ? nodes != all_nodes || edges != all_edges : nodes > all_nodes || edges > all_edges)
fail(root, root_pos_,
"unreachable nodes or edges: reached " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges of " + std::to_string(all_nodes) + " and " + std::to_string(all_edges));
// The table: one entry per node, each under its node's key.
size_t entries = 0;
for (size_t s = 0; s < tree_.table_slots(); s++) {
const u32 n = tree_.table_node(s);
if (!n) continue;
entries++;
if (n >= tree_.nodes_used() || tree_.table_key_hi(s) != u32(tree_.node(n).key >> 32))
fail(root, root_pos_, "table slot " + std::to_string(s) + " points to a wrong node");
}
if (entries != all_nodes || tree_.table_entries() != all_nodes)
fail(root, root_pos_,
"table has " + std::to_string(entries) + " entries for " + std::to_string(all_nodes) + " nodes");
uci_io::send("info string tree verified: " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges reachable, " + std::to_string(all_nodes) + " nodes in the arena, " +
std::to_string(entries) + " table entries");
}
#endif
u32 Searcher::create_node(const Position& pos, bool is_root, float& value) {
const u32 idx = tree_.alloc_node();
if (!idx) return 0;
Node& node = tree_.node(idx);
node = Node{};
node.key = pos.key;
node.check = position_check(pos);
// Only what the position itself decides. Repetitions and the 50-move rule
// depend on the path and are judged on every playout instead. The root
// must always produce a move, so it is never declared drawn.
if (!has_legal_move(pos)) {
node.state = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
value = node.state == TERMINAL_LOSS ? -1.0f : 0.0f;
} else if (!is_root && pos.insufficient_material()) {
node.state = TERMINAL_DRAW;
value = 0.0f;
} else {
value = eval::value(pos);
}
node.visits = node.base = 1;
node.u = node.q = -value;
tree_.insert(idx);
return idx;
}
bool Searcher::expand(u32 idx, const Position& pos) {
MoveList moves;
generate_legal(pos, moves);
const u32 first = tree_.alloc_edges(u32(moves.size()));
if (!first) {
// Out of memory: this time the node stays a leaf; the tree is collected
// right after this playout, so the next visit can expand it.
gc_pending_ = true;
return false;
}
// The butterfly history of each move shifts its logit. The priors are a
// snapshot: later history updates do not change them.
float bias[256];
for (int i = 0; i < moves.size(); i++)
bias[i] = float(butterfly_.get(pos.stm, moves[i])) / ButterflyHistory::LOGIT_SCALE;
float priors[256];
eval::policy(pos, moves, params.policy_temperature, bias, priors);
for (int i = 0; i < moves.size(); i++) {
Edge& e = tree_.edge(first + u32(i));
e = Edge{};
e.move = moves[i].raw();
e.policy = u16(std::lround(std::clamp(priors[i], 0.0f, 1.0f) * 65535.0f));
}
Node& node = tree_.node(idx);
node.first_edge = first;
node.num_edges = u8(moves.size());
node.state = EXPANDED;
return true;
}
u32 Searcher::select_edge(u32 idx) const {
const Node& node = tree_.node(idx);
// node.q is from the view of the side that moved into this node, so the side
// to move here sees -q. Visits are N(n), the node's own evaluation included.
const float parent_q = node.visits ? -node.q : 0.0f;
float visited_policy = 0.0f;
for (u32 i = 0; i < node.num_edges; i++) {
const Edge& e = tree_.edge(node.first_edge + i);
if (e.visits) visited_policy += e.prior();
}
const float fpu = parent_q - params.fpu_reduction * std::sqrt(visited_policy);
// Exploration grows with the visits (Monty's scaling): a node searched a
// lot keeps giving its other moves a chance.
const float n = float(std::max<u32>(node.visits, 1));
// The root, where the move is chosen, explores more.
const float base_cpuct = idx == tree_.root() ? params.root_cpuct : params.cpuct;
const float cpuct = base_cpuct * (1.0f + std::log((n + params.cpuct_visit_scale) / params.cpuct_visit_scale));
const float explore = cpuct * std::sqrt(n);
u32 best = node.first_edge;
float best_score = -1e30f;
for (u32 i = 0; i < node.num_edges; i++) {
const u32 c = node.first_edge + i;
const Edge& e = tree_.edge(c);
// The child's Q is from the view of the side to move here.
const float q = e.visits ? visited_edge_q(e) : fpu;
const float score = q + explore * e.prior() / float(1 + e.visits);
if (score > best_score) {
best_score = score;
best = c;
}
}
return best;
}
void Searcher::recompute_q(Node& node) const {
// q = (base * u - sum (N - D) * c.q) / N, in the view of the side that
// moved into the node. Children's Q are from the view of the side to move
// here, hence the minus; path draws count 0.
double sum = double(node.base) * double(node.u);
for (u32 i = 0; i < node.num_edges; i++) {
const Edge& e = tree_.edge(node.first_edge + i);
const u32 w = e.visits - e.draws;
if (w) sum -= double(w) * double(tree_.node(e.child).q);
}
node.q = float(sum / double(node.visits));
}
void Searcher::playout() {
Position pos = root_pos_;
history_.resize(root_history_size_);
path_.clear();
edge_path_.clear();
// How the playout ended; it decides what happens to the last node.
enum Leaf { NEW_NODE, TERMINAL, NOT_EXPANDED, PATH_DRAW, STOPPED } leaf;
u32 idx = tree_.root();
path_.push_back(idx);
int depth = 0;
float value; // for the side to move at the end of the playout
for (;;) {
Node& node = tree_.node(idx);
if (node.state == TERMINAL_LOSS || node.state == TERMINAL_DRAW) {
value = -node.u;
leaf = TERMINAL;
break;
}
// A node's first visit created and evaluated it; the second creates
// its edges (moves, priors, memory).
if (node.state == UNEXPANDED && !expand(idx, pos)) {
value = -node.q;
leaf = NOT_EXPANDED;
break;
}
const u32 e = select_edge(idx);
Edge& edge = tree_.edge(e);
pos.make_move(Move::from_raw(edge.move));
history_.push_back(pos.key);
edge_path_.push_back(e);
depth++;
// Draws by repetition or the 50-move rule belong to this path, not to
// the position, so they are judged before looking for its node and
// only ever recorded on the edge. Mate on the 100th half-move is still
// mate.
if (is_repetition(pos) ||
(pos.halfmove >= 100 &&
!(edge.child ? tree_.node(edge.child).state == TERMINAL_LOSS : pos.in_check() && !has_legal_move(pos)))) {
value = 0.0f;
leaf = PATH_DRAW;
break;
}
if (!edge.child) {
// The first time this move is chosen here. Its position may already
// have a node, reached by another move order: link to it and go on.
const u16 check = position_check(pos);
u32 child = tree_.find(pos.key, check);
if (!child) {
child = create_node(pos, false, value);
if (!child) {
// The node arena is full. This playout is dropped without
// a trace and the graph is collected right after it.
gc_pending_ = true;
return;
}
edge.child = child;
path_.push_back(child);
leaf = NEW_NODE;
break;
}
edge.child = child;
}
idx = edge.child;
path_.push_back(idx);
// Stop rule (KataGo, plan variant 5a): a child that already has more
// visits than this edge (other move orders reached it) is ahead of
// what this edge needs. The playout ends there: the edge counts the
// visit with the child's current value, and the child is left as it
// is. In a tree the two counts are equal and this never happens. The
// depth limit ends a playout the same way.
if (tree_.node(idx).visits > edge.visits || depth >= MAX_PLAYOUT_DEPTH) {
value = -tree_.node(idx).q;
leaf = STOPPED;
break;
}
}
// The last node. A new node already has its one visit (N = base = 1); a
// terminal node and a node that could not be expanded count one more visit
// of their own value (q = u stays). A path draw has no node, and a node
// where the playout stopped is left as it is: only the edge into it counts
// the visit.
if (leaf == TERMINAL || leaf == NOT_EXPANDED) {
Node& node = tree_.node(path_.back());
node.visits++;
node.base++;
}
// Up the path: each edge counts the visit (and the draw), and its parent
// node recomputes its Q from its children. `value` is from the view of
// the side to move at the end, so its sign flips at every step back. In
// centipawns it scores each move in the butterfly history, for the side
// that played it (the side to move at ply j).
int bonus = eval::q_to_cp(std::clamp(value, -0.998f, 0.998f));
for (size_t j = edge_path_.size(); j-- > 0;) {
bonus = -bonus;
Edge& e = tree_.edge(edge_path_[j]);
e.visits++;
if (leaf == PATH_DRAW && j + 1 == edge_path_.size()) e.draws++;
butterfly_.update(root_pos_.stm ^ int(j & 1), Move::from_raw(e.move), bonus);
Node& node = tree_.node(path_[j]);
node.visits++;
recompute_q(node);
}
iterations_++;
depth_sum_ += u64(depth);
seldepth_ = std::max(seldepth_, depth);
}
u32 Searcher::best_edge(u32 idx) const {
const Node& node = tree_.node(idx);
u32 best = 0;
for (u32 i = 0; i < node.num_edges; i++) {
const u32 c = node.first_edge + i;
if (!best) {
best = c;
continue;
}
const Edge& a = tree_.edge(c);
const Edge& b = tree_.edge(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 ? edge_q(a) > edge_q(b) : a.policy > b.policy)
best = c;
}
return best;
}
void Searcher::print_info() const {
const Node& root = tree_.node(tree_.root());
const i64 ms = elapsed_ms();
const u32 best = best_edge(tree_.root());
std::ostringstream out;
out << "info depth " << (iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0) << " seldepth "
<< seldepth_;
const float q = best && tree_.edge(best).visits ? edge_q(tree_.edge(best)) : -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_.fill_permille();
out << " pv";
for (const Move m : principal_variation()) out << ' ' << root_pos_.uci(m);
uci_io::send(out.str());
}
std::vector<Move> Searcher::principal_variation() const {
// The best edge from each node. The graph can have cycles, so the line
// also ends after a move into a position it or the game has seen before
// (a draw), and after 64 plies.
std::vector<Move> pv;
std::vector<u64> keys(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_));
Position pos = root_pos_;
u32 idx = tree_.root();
for (int ply = 0; ply < 64; ply++) {
const u32 c = best_edge(idx);
if (!c || !tree_.edge(c).visits) break;
const Edge& e = tree_.edge(c);
pv.push_back(Move::from_raw(e.move));
pos.make_move(Move::from_raw(e.move));
if (!e.child || std::find(keys.begin(), keys.end(), pos.key) != keys.end()) break;
keys.push_back(pos.key);
idx = e.child;
}
return pv;
}
void Searcher::draw_dashboard(bool done) {
const Node& root = tree_.node(tree_.root());
const u32 best = best_edge(tree_.root());
const i64 ms = elapsed_ms();
pretty::Dashboard d;
d.root = root_pos_;
d.depth = int(iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0);
d.seldepth = seldepth_;
d.playouts = iterations_;
d.nps = ms ? iterations_ * 1000 / u64(ms) : iterations_;
d.ms = ms;
d.time_limit_ms = time_limit_ms_;
d.node_limit = node_limit_;
d.hashfull = tree_.fill_permille();
d.cp = eval::q_to_cp(best && tree_.edge(best).visits ? edge_q(tree_.edge(best)) : -root.q);
d.pv = principal_variation();
for (u32 i = 0; i < root.num_edges; i++) {
const Edge& e = tree_.edge(root.first_edge + i);
d.moves.push_back({Move::from_raw(e.move), e.visits, eval::q_to_cp(edge_q(e)), e.prior()});
}
d.reused = reused_;
d.collections = gc_runs_;
d.done = done;
uci_io::send(live_.draw(d));
}
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(prev_history_);
root_pos_ = root;
}
#endif
size_t reused = reuse_tree(root);
// The root's edges must be exactly its legal moves. Inside the graph that
// rests on the 80-bit key and check; the root is checked in full.
if (reused && !root_edges_valid(root)) reused = 0;
if (!reused) clear_tree(root);
#ifdef RIGBY_VERIFY_TREE
if (reused) verify_tree(history_);
#endif
if (print && !pretty && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes");
iterations_ = 0;
depth_sum_ = 0;
seldepth_ = 0;
gc_pending_ = false;
gc_runs_ = 0;
reused_ = reused;
node_limit_ = limits.nodes;
compute_time_limit(limits);
SearchResult result;
MoveList root_moves;
generate_legal(root, root_moves);
if (root_moves.empty()) {
tree_valid_ = false;
if (print && pretty)
uci_io::send(pretty::note(root.in_check() ? "checkmate, no legal moves" : "stalemate, no legal moves"));
else if (print)
uci_io::send("info depth 0 score " + std::string(root.in_check() ? "mate 0" : "cp 0"));
return result;
}
if (print && pretty) live_.begin();
// The root needs its edges before the first playout, so that even a
// single playout leaves a move to play.
if (tree_.node(tree_.root()).state == UNEXPANDED && !expand(tree_.root(), root)) {
clear_tree(root);
gc_pending_ = false;
expand(tree_.root(), root);
}
// Root edge visits brought along by tree reuse, for smart pruning. The
// root's edges keep their order through collections.
root_start_visits_.clear();
{
const Node& r = tree_.node(tree_.root());
for (u32 i = 0; i < r.num_edges; i++) root_start_visits_.push_back(tree_.edge(r.first_edge + i).visits);
}
// UCI reports once a second; the dashboard for a human is redrawn in place
// ten times a second.
const i64 info_interval = pretty ? 100 : 1000;
const u64 info_mask = pretty ? 255 : 1023;
i64 next_info = pretty ? 0 : 1000;
do {
playout();
if (gc_pending_) {
tree_.collect_garbage(GC_KEEP_FRACTION);
gc_pending_ = false;
gc_runs_++;
#ifdef RIGBY_VERIFY_TREE
verify_tree(std::vector<u64>(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)),
true);
#endif
}
if (print && (iterations_ & info_mask) == 0) {
const i64 ms = elapsed_ms();
if (ms >= next_info) {
next_info = ms + info_interval;
if (pretty) draw_dashboard(false);
else print_info();
}
}
} while (!should_stop(limits));
if (print && pretty) {
draw_dashboard(true);
} else if (print) {
print_info();
if (gc_runs_) uci_io::send("info string tree collected " + std::to_string(gc_runs_) + " times");
}
#ifdef RIGBY_VERIFY_TREE
verify_tree(std::vector<u64>(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)));
#endif
const u32 best = best_edge(tree_.root());
result.best = Move::from_raw(tree_.edge(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;
}
#ifdef RIGBY_VERIFY_TREE
namespace {
[[noreturn]] void self_test_failed(const std::string& what) {
std::cerr << "VERIFY FAILED: " << what << std::endl;
std::abort();
}
// What a node looked like, to compare after a collection or a reroot.
struct NodeSnapshot {
u64 key;
u32 visits;
float q, u;
u32 base;
u8 state;
u16 check;
// (move, policy, visits, draws, child's key or 0) per edge
std::vector<std::tuple<u16, u16, u32, u32, u64>> edges;
};
} // namespace
void Searcher::self_test() {
// (a) The incremental key equals the key of the same position set up from
// its FEN, along random games, standard and Chess960.
{
static constexpr const char* FENS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"rnbqkbnr/ppp1p1pp/8/3pPp2/8/8/PPPP1PPP/RNBQKBNR w KQkq f6 0 3",
"bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9",
"2nnrbkr/p1qppppp/8/1ppb4/6PP/3PP3/PPP2P2/BQNNRBKR w HEhe - 1 9",
"qrbnnkrb/pppppppp/8/8/8/8/PPPPPPPP/QRBNNKRB w GBgb - 0 1",
"rkrnnqbb/pppppppp/8/8/8/8/PPPPPPPP/RKRNNQBB w CAca - 0 1",
};
std::mt19937_64 rng(20261116);
u64 plies = 0;
for (const char* fen : FENS) {
for (int game = 0; game < 50; game++) {
Position pos;
if (!pos.set_fen(fen)) self_test_failed(std::string("bad fen ") + fen);
for (int ply = 0; ply < 300; ply++) {
MoveList moves;
generate_legal(pos, moves);
if (moves.empty()) break;
const Move m = moves[int(rng() % u64(moves.size()))];
const std::string before = pos.fen();
pos.make_move(m);
Position fresh;
if (!fresh.set_fen(pos.fen())) self_test_failed("fen does not parse: " + pos.fen());
if (fresh.key != pos.key || position_check(fresh) != position_check(pos))
self_test_failed("incremental key differs after " + before + " " + pos.uci(m) + " -> " +
pos.fen());
plies++;
}
}
}
uci_io::send("info string verify (a) keys: " + std::to_string(plies) + " plies ok");
}
// (b) Garbage collection and rerooting keep everything they keep exactly.
// A node is identified by its position's key, which is unique in the graph.
// (d) After each of them, verify_tree also checks the table against the
// surviving nodes.
const auto snapshot = [&](u32 from) {
std::map<u64, NodeSnapshot> snap;
std::vector<u8> seen(tree_.nodes_used(), 0);
std::vector<u32> stack{from};
seen[from] = 1;
while (!stack.empty()) {
const u32 idx = stack.back();
stack.pop_back();
const Node& n = tree_.node(idx);
NodeSnapshot s{n.key, n.visits, n.q, n.u, n.base, n.state, n.check, {}};
for (u32 i = 0; i < n.num_edges; i++) {
const Edge& e = tree_.edge(n.first_edge + i);
s.edges.emplace_back(e.move, e.policy, e.visits, e.draws, e.child ? tree_.node(e.child).key : 0);
if (e.child && !seen[e.child]) {
seen[e.child] = 1;
stack.push_back(e.child);
}
}
if (!snap.emplace(n.key, std::move(s)).second) self_test_failed("two nodes with one key");
}
return snap;
};
// Walks the current graph from the root and compares it with `before`.
// Returns the number of nodes; `pruned_max` / `kept_min` get the largest
// visits of a node that lost its edges and the smallest of a non-root node
// that kept them.
const auto compare = [&](const std::map<u64, NodeSnapshot>& before, bool allow_pruning, u32& pruned_max,
u32& kept_min) {
size_t count = 0;
pruned_max = 0;
kept_min = ~0u;
std::vector<u8> seen(tree_.nodes_used(), 0);
std::vector<u32> stack{tree_.root()};
seen[tree_.root()] = 1;
while (!stack.empty()) {
const u32 idx = stack.back();
stack.pop_back();
count++;
const Node& n = tree_.node(idx);
const auto it = before.find(n.key);
if (it == before.end()) self_test_failed("a node appeared from nowhere");
const NodeSnapshot& s = it->second;
if (n.check != s.check || n.visits != s.visits || n.q != s.q)
self_test_failed("node changed (check, visits or q)");
if (!s.edges.empty() && !n.num_edges) {
if (!allow_pruning) self_test_failed("a node lost its edges in a reroot");
if (n.state != UNEXPANDED || n.first_edge || n.u != n.q || n.base != n.visits)
self_test_failed("pruned node not reset properly");
pruned_max = std::max(pruned_max, n.visits);
continue;
}
if (n.state != s.state || n.u != s.u || n.base != s.base || n.num_edges != s.edges.size())
self_test_failed("node changed (state, u, base or edges)");
if (n.num_edges && idx != tree_.root()) kept_min = std::min(kept_min, n.visits);
for (u32 i = 0; i < n.num_edges; i++) {
const Edge& e = tree_.edge(n.first_edge + i);
if (std::make_tuple(e.move, e.policy, e.visits, e.draws, e.child ? tree_.node(e.child).key : 0) !=
s.edges[i])
self_test_failed("edge changed");
if (e.child && !seen[e.child]) {
seen[e.child] = 1;
stack.push_back(e.child);
}
}
}
return count;
};
static constexpr const char* SEARCH_FENS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r1bq1rk1/ppp2ppp/2np1n2/2b1p3/2B1P3/2NP1N2/PPP2PPP/R1BQ1RK1 w - - 0 7",
"8/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1",
"bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9",
};
for (const char* fen : SEARCH_FENS) {
Position root;
root.set_fen(fen);
SearchLimits limits;
limits.nodes = 30000;
// Collections down to a half, a quarter and an eighth of the graph.
new_game();
stop_flag = false;
search(root, {root.key}, limits, false);
for (int round = 1; round <= 3; round++) {
const auto before = snapshot(tree_.root());
const size_t node_target = tree_.nodes_used() >> round, edge_target = tree_.edges_used() >> round;
tree_.collect_garbage(node_target, edge_target);
if (tree_.nodes_used() > node_target || tree_.edges_used() > edge_target)
self_test_failed("collection kept more than its target");
u32 pruned_max, kept_min;
const size_t count = compare(before, true, pruned_max, kept_min);
if (count != tree_.nodes_used() - 1) self_test_failed("node count differs after collection");
if (pruned_max >= kept_min) self_test_failed("pruned a node with more visits than one kept");
verify_tree({root.key}, true);
uci_io::send("info string verify (b) gc " + std::string(fen) + ": " + std::to_string(before.size()) +
" -> " + std::to_string(count) + " nodes ok");
uci_io::send("info string verify (d) table after gc: " + std::to_string(tree_.table_entries()) +
" entries for " + std::to_string(count) + " nodes ok");
}
// Reroot two plies down the most visited line, as between two moves of a game.
new_game();
stop_flag = false;
search(root, {root.key}, limits, false);
std::vector<u64> history{root.key};
Position pos = root;
u32 idx = tree_.root();
for (int ply = 0; ply < 2; ply++) {
const u32 e = best_edge(idx);
if (!e || !tree_.edge(e).child) break;
pos.make_move(Move::from_raw(tree_.edge(e).move));
history.push_back(pos.key);
idx = tree_.edge(e).child;
}
if (idx == tree_.root() || tree_.node(idx).state != EXPANDED) self_test_failed("no node to reroot to");
const auto before = snapshot(idx);
const size_t nodes_before = tree_.nodes_used(), edges_before = tree_.edges_used();
tree_.reroot(idx);
// A reroot only moves the root: everything stays where it was.
u32 pruned_max, kept_min;
const size_t count = compare(before, false, pruned_max, kept_min);
if (count != before.size() || tree_.nodes_used() != nodes_before || tree_.edges_used() != edges_before)
self_test_failed("reroot changed the graph");
root_pos_ = pos;
verify_tree(history);
// The next collection (with room for everything) keeps exactly what the
// new root reaches, unchanged.
tree_.collect_garbage(tree_.node_capacity(), tree_.edge_capacity());
const size_t kept = compare(before, false, pruned_max, kept_min);
if (kept != before.size() || kept != tree_.nodes_used() - 1)
self_test_failed("collection after a reroot kept the wrong nodes");
verify_tree(history, true);
uci_io::send("info string verify (b) reroot " + std::string(fen) + ": " + std::to_string(nodes_before - 1) +
" nodes, " + std::to_string(count) + " reachable from the new root, collected to " +
std::to_string(kept) + " ok");
uci_io::send("info string verify (d) table after reroot and collection: " +
std::to_string(tree_.table_entries()) + " entries for " + std::to_string(kept) + " nodes ok");
}
// (c) Draws of the path never leak into nodes: search positions where
// repetitions or the 50-move rule are forced or frequent. verify_tree (at
// the end of each search) recomputes every node's state from its position
// alone; here the draws must also show up on edges.
struct RepetitionCase {
const char* fen;
const char* moves;
bool fifty_move; // draws by the 50-move rule must appear
};
static constexpr RepetitionCase REPETITION_CASES[] = {
{"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "g1f3 g8f6 f3g1 f6g8 g1f3 g8f6", false},
{"6k1/6p1/8/6KQ/1r6/q2b4/8/8 w - - 0 32", "", false},
{"8/8/8/4k3/8/8/2KR4/8 w - - 95 100", "", true},
{"8/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1", "", false},
{"8/5pk1/6p1/7p/7P/6P1/5PK1/8 w - - 0 40", "", false},
};
for (const RepetitionCase& c : REPETITION_CASES) {
Position root;
if (!root.set_fen(c.fen)) self_test_failed(std::string("bad fen ") + c.fen);
std::vector<u64> history{root.key};
std::istringstream moves(c.moves);
for (std::string uci; moves >> uci;) {
const Move m = root.parse_uci(uci);
if (!m) self_test_failed("bad move " + uci);
root.make_move(m);
history.push_back(root.key);
}
SearchLimits limits;
limits.nodes = 30000;
new_game();
stop_flag = false;
search(root, history, limits, false); // ends with verify_tree(history)
u64 draw_edges = 0, draw_visits = 0, fifty_edges = 0;
std::vector<u8> seen(tree_.nodes_used(), 0);
std::vector<std::pair<u32, Position>> stack{{tree_.root(), root}};
seen[tree_.root()] = 1;
while (!stack.empty()) {
const auto [idx, pos] = stack.back();
stack.pop_back();
const Node& n = tree_.node(idx);
for (u32 i = 0; i < n.num_edges; i++) {
const Edge& e = tree_.edge(n.first_edge + i);
Position next = pos;
next.make_move(Move::from_raw(e.move));
if (e.draws) {
draw_edges++;
draw_visits += e.draws;
// The clock of the first path that reached the node.
if (next.halfmove >= 100) fifty_edges++;
}
if (e.child && !seen[e.child]) {
seen[e.child] = 1;
stack.push_back({e.child, next});
}
}
}
if (!draw_visits) self_test_failed(std::string("no draws of the path recorded on edges: ") + c.fen);
if (c.fifty_move && !fifty_edges) self_test_failed(std::string("no 50-move draws on edges: ") + c.fen);
uci_io::send("info string verify (c) " + std::string(c.fen) + (*c.moves ? " moves " : "") + c.moves +
": " + std::to_string(draw_visits) + " draw visits on " + std::to_string(draw_edges) +
" edges (" + std::to_string(fifty_edges) + " at half-move 100+), node states ok");
}
new_game();
uci_io::send("info string verify passed");
}
#endif
} // namespace rigby