Monte-Carlo graph search (MCGS steps 2, 3 and 3b) #23

Merged
claude merged 19 commits from mcgs-step3-reroot into main 2026-11-16 23:18:22 +01:00
2 changed files with 411 additions and 192 deletions
Showing only changes of commit 6629525938 - Show all commits

No files matched your search

+326 -163
View File
@@ -1,6 +1,7 @@
#include "mcts.h" #include "mcts.h"
#include <algorithm> #include <algorithm>
#include <bit>
#include <cmath> #include <cmath>
#include <cstring> #include <cstring>
#include <iostream> #include <iostream>
@@ -16,113 +17,166 @@ namespace rigby {
// Tree // 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) { void Tree::resize_bytes(size_t bytes) {
const size_t count = std::max<size_t>(bytes / sizeof(Node), 1024); // A node costs its own 32 bytes plus EDGES_PER_NODE edges of 16.
nodes_.assign(count, Node{}); const size_t per_node = sizeof(Node) + EDGES_PER_NODE * sizeof(Edge);
const size_t node_count = std::max<size_t>(bytes / per_node, 1024);
nodes_.assign(node_count, Node{});
nodes_.shrink_to_fit(); nodes_.shrink_to_fit();
edges_.assign(node_count * EDGES_PER_NODE, Edge{});
edges_.shrink_to_fit();
clear(); clear();
} }
void Tree::clear() { void Tree::clear() {
used_ = 2; // index 0 is the null child, index 1 is the root nodes_used_ = 2; // index 0 is the null node, index 1 the root
nodes_[root()] = Node{}; edges_used_ = 1; // index 0 is the null edge
root_ = 1;
nodes_[root_] = Node{};
} }
u32 Tree::alloc(u32 count) { u32 Tree::alloc_node() {
if (used_ + count > nodes_.size()) return 0; if (nodes_used_ >= nodes_.size()) return 0;
const u32 idx = u32(used_); return u32(nodes_used_++);
used_ += count; }
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; return idx;
} }
size_t Tree::reroot(u32 new_root) { size_t Tree::reroot(u32 new_root) {
if (new_root == root()) return used_; if (new_root == root_) return nodes_used_ - 1;
return compact(new_root, 0); return compact(new_root, 0);
} }
size_t Tree::collect_garbage(double keep_fraction) { size_t Tree::collect_garbage(double keep_fraction) {
const size_t target = size_t(double(nodes_.size()) * keep_fraction); return collect_garbage(size_t(double(nodes_.size()) * keep_fraction), size_t(double(edges_.size()) * keep_fraction));
return compact(root(), prune_threshold(target));
} }
u32 Tree::prune_threshold(size_t target) const { size_t Tree::collect_garbage(size_t node_target, size_t edge_target) {
// A node's children survive a collection with threshold T when the node has return compact(root_, prune_threshold(node_target, edge_target));
// at least T visits. Visits only shrink going down the tree, so every }
// ancestor of such a node survives too, and the size kept for a threshold is
// just the children of all nodes with at least that many visits. 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 has
// at least T visits, and the child nodes of those edges stay. Visits only
// shrink going down a tree, so every ancestor of such a node survives too,
// and the size kept for a threshold is just the edges and child nodes of
// all nodes with at least that many visits.
constexpr u32 CAP = 1 << 16; 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<u64> children_by_visits(CAP + 1, 0);
std::vector<u32> stack{root()}; std::vector<u32> stack{root_};
while (!stack.empty()) { while (!stack.empty()) {
const Node& node = nodes_[stack.back()]; const Node& node = nodes_[stack.back()];
stack.pop_back(); stack.pop_back();
if (!node.first_child) continue; if (!node.first_edge) continue;
children_by_visits[std::min(node.visits, CAP)] += node.num_children; const u32 bucket = std::min(node.visits, CAP);
for (u32 i = 0; i < node.num_children; i++) stack.push_back(node.first_child + i); edges_by_visits[bucket] += node.num_edges;
for (u32 i = 0; i < node.num_edges; i++) {
const u32 child = edges_[node.first_edge + i].child;
if (!child) continue;
children_by_visits[bucket]++;
stack.push_back(child);
}
} }
u64 kept = 2; // null slot and root u64 kept_nodes = 2; // null node and root
u64 kept_edges = 1; // null edge
for (u32 v = CAP; v >= 1; v--) { for (u32 v = CAP; v >= 1; v--) {
if (kept + children_by_visits[v] > target) return v + 1; if (kept_nodes + children_by_visits[v] > node_target || kept_edges + edges_by_visits[v] > edge_target)
kept += children_by_visits[v]; return v + 1;
kept_nodes += children_by_visits[v];
kept_edges += edges_by_visits[v];
} }
return 1; return 1;
} }
size_t Tree::compact(u32 new_root, u32 min_visits) { size_t Tree::compact(u32 new_root, u32 min_visits) {
// Every child block that stays, as (old first index, size). Nodes below the // Mark: everything reachable from the new root stays. A node below the
// visit threshold lose their children and become leaves again; they keep // visit threshold loses its edges and becomes a leaf again; it keeps its
// their visits and Q, and get expanded anew if search comes back to them. // visits and Q (also as u and base) and gets expanded anew if search
// comes back 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<std::pair<u32, u32>> blocks;
std::vector<u32> stack{new_root}; std::vector<u32> stack{new_root};
marked[new_root] = 1;
while (!stack.empty()) { while (!stack.empty()) {
const u32 idx = stack.back(); const u32 idx = stack.back();
stack.pop_back(); stack.pop_back();
Node& node = nodes_[idx]; Node& node = nodes_[idx];
if (!node.first_child) continue; if (!node.first_edge) continue;
if (idx != new_root && node.visits < min_visits) { if (idx != new_root && node.visits < min_visits) {
node.first_child = 0; node.first_edge = 0;
node.num_children = 0; node.num_edges = 0;
node.state = UNEXPANDED; node.state = UNEXPANDED;
node.u = node.q;
node.base = node.visits;
continue; continue;
} }
blocks.emplace_back(node.first_child, node.num_children); blocks.emplace_back(node.first_edge, node.num_edges);
for (u32 i = 0; i < node.num_children; i++) stack.push_back(node.first_child + i); 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);
}
}
} }
// A block is always allocated after its parent's block, so packing the kept // Forwarding: the marked nodes and the kept edge blocks get new places in
// blocks in their original order only ever moves them towards the front, and // their old index order. Every destination is then at or before its
// never onto a block that has not moved yet. That allows doing it in place. // 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::sort(blocks.begin(), blocks.end());
std::vector<u32> dest(blocks.size()); std::vector<u32> dest(blocks.size());
u32 next = 2; u32 next_edge = 1;
for (size_t i = 0; i < blocks.size(); i++) { for (size_t i = 0; i < blocks.size(); i++) {
dest[i] = next; dest[i] = next_edge;
next += blocks[i].second; next_edge += blocks[i].second;
} }
const auto remap_edges = [&](u32 old_first) -> u32 {
const auto remap = [&](u32 old_first) -> u32 {
if (!old_first) return 0; if (!old_first) return 0;
const auto it = std::lower_bound(blocks.begin(), blocks.end(), std::make_pair(old_first, u32(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())]; return dest[size_t(it - blocks.begin())];
}; };
// The new root's own slot may be overwritten by a moved block, so take it first. for (u32 i = 1; i < nodes_used_; i++) {
Node new_root_node = nodes_[new_root]; if (!marked[i]) continue;
new_root_node.first_child = remap(new_root_node.first_child); 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++) { for (size_t i = 0; i < blocks.size(); i++) {
const auto [first, count] = blocks[i]; const auto [first, count] = blocks[i];
if (dest[i] != first) std::memmove(&nodes_[dest[i]], &nodes_[first], size_t(count) * sizeof(Node)); if (dest[i] != first) std::memmove(&edges_[dest[i]], &edges_[first], size_t(count) * sizeof(Edge));
for (u32 j = 0; j < count; j++) { for (u32 j = 0; j < count; j++) {
Node& node = nodes_[dest[i] + j]; Edge& e = edges_[dest[i] + j];
node.first_child = remap(node.first_child); e.child = forward[e.child];
} }
} }
nodes_[root()] = new_root_node; root_ = forward[new_root];
used_ = next; nodes_used_ = next_node;
return used_ - 1; // everything but the null slot edges_used_ = next_edge;
return nodes_used_ - 1; // everything but the null node
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -131,6 +185,13 @@ size_t Tree::compact(u32 new_root, u32 min_visits) {
Searcher::Searcher() { set_hash(64); } Searcher::Searcher() { set_hash(64); }
void Searcher::clear_tree(const Position& root) {
tree_.clear();
Node& node = tree_.node(tree_.root());
node.key = root.key;
node.check = position_check(root);
}
i64 Searcher::elapsed_ms() const { i64 Searcher::elapsed_ms() const {
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time_).count(); return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time_).count();
} }
@@ -166,20 +227,20 @@ bool Searcher::best_move_settled(i64 ms, i64 limit_ms) const {
// visits that nothing could overtake it, which would stop every search // visits that nothing could overtake it, which would stop every search
// at once. The move leading this search must also be the one played. // at once. The move leading this search must also be the one played.
if (ms <= 0 || iterations_ < 256) return false; if (ms <= 0 || iterations_ < 256) return false;
const Node& root = tree_[Tree::root()]; const Node& root = tree_.node(tree_.root());
if (root_start_visits_.size() != root.num_children) return false; if (root_start_visits_.size() != root.num_edges) return false;
u32 first = 0, second = 0, leader = 0; u32 first = 0, second = 0, leader = 0;
for (u32 i = 0; i < root.num_children; i++) { for (u32 i = 0; i < root.num_edges; i++) {
const u32 v = tree_[root.first_child + i].visits - root_start_visits_[i]; const u32 v = tree_.edge(root.first_edge + i).visits - root_start_visits_[i];
if (v > first) { if (v > first) {
second = first; second = first;
first = v; first = v;
leader = root.first_child + i; leader = root.first_edge + i;
} else if (v > second) { } else if (v > second) {
second = v; second = v;
} }
} }
if (leader != best_child(Tree::root())) return false; if (leader != best_edge(tree_.root())) return false;
const double remaining = const double remaining =
double(iterations_) / double(ms) * double(limit_ms - ms) / SMART_PRUNING_FACTOR; double(iterations_) / double(ms) * double(limit_ms - ms) / SMART_PRUNING_FACTOR;
return double(second) + remaining < double(first); return double(second) + remaining < double(first);
@@ -225,18 +286,21 @@ size_t Searcher::reuse_tree(const Position& root) {
!std::equal(prev_history_.begin(), prev_history_.end(), history_.begin())) !std::equal(prev_history_.begin(), prev_history_.end(), history_.begin()))
return 0; return 0;
u32 idx = Tree::root(); u32 idx = tree_.root();
Position pos = prev_root_; Position pos = prev_root_;
for (size_t i = prev_history_.size(); i < history_.size(); i++) { for (size_t i = prev_history_.size(); i < history_.size(); i++) {
const Node& node = tree_[idx]; const Node& node = tree_.node(idx);
if (node.state != EXPANDED) return 0; if (node.state != EXPANDED) return 0;
u32 next = 0; u32 next = 0;
for (u32 c = 0; c < node.num_children && !next; c++) { for (u32 c = 0; c < node.num_edges && !next; c++) {
const Edge& e = tree_.edge(node.first_edge + c);
Position child = pos; Position child = pos;
child.make_move(Move::from_raw(tree_[node.first_child + c].move)); child.make_move(Move::from_raw(e.move));
if (child.key == history_[i]) { if (child.key == history_[i]) {
next = node.first_child + c; // A move search never tried has no node to continue from.
if (!e.child) return 0;
next = e.child;
pos = child; pos = child;
} }
} }
@@ -246,60 +310,126 @@ size_t Searcher::reuse_tree(const Position& root) {
// A node that was a draw by repetition or the 50-move rule inside the old // 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. // 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; if (pos.key != root.key || tree_.node(idx).state != EXPANDED) return 0;
return tree_.reroot(idx); return tree_.reroot(idx);
} }
#ifdef RIGBY_VERIFY_TREE #ifdef RIGBY_VERIFY_TREE
// Debug check: the tree must still describe legal play from the root, and every // Debug check, from the root as `root_pos_` with the game history `history`
// expanded node must have at least one visit more than its children together // (ending with the root's key):
// (more when it was evaluated as a leaf while the tree was full). // - every node is reached exactly once (in-degree 1, the root 0), and the
void Searcher::verify_tree() const { // arenas hold nothing else;
struct Item { // - a node's key and check match its position, and its state is the one
// evaluate_leaf gives that position on this path;
// - an expanded node has one edge per legal move;
// - an edge has a child node exactly when it has visits, with as many visits
// as the child (a tree), and no draws yet;
// - every expanded node has at least one visit more than its edges together
// (more when it was evaluated as a leaf while the tree was full); the root
// is expanded before its first visit, so it may have exactly as many;
// - Q and u are finite and in [-1, 1].
void Searcher::verify_tree(const std::vector<u64>& history) const {
const auto fail = [&](u32 idx, const Position& pos, const std::string& what) {
const Node& n = tree_.node(idx);
std::cerr << "TREE CORRUPT at node " << idx << " (" << pos.fen() << "): " << what << " visits=" << n.visits
<< " q=" << n.q << " state=" << int(n.state) << " edges=" << int(n.num_edges)
<< " first=" << n.first_edge << " nodes_used=" << tree_.nodes_used()
<< " edges_used=" << tree_.edges_used() << std::endl;
std::abort();
};
std::vector<u32> in_degree(tree_.nodes_used(), 0);
std::vector<u64> keys = history;
struct Frame {
u32 idx; u32 idx;
Position pos; Position pos;
int depth;
u32 next = 0;
}; };
std::vector<Item> stack{{Tree::root(), root_pos_}}; std::vector<Frame> stack;
u64 checked = 0; u64 nodes = 0, edges = 0;
while (!stack.empty()) {
const Item item = stack.back();
stack.pop_back();
const Node& node = tree_[item.idx];
checked++;
if (node.state != EXPANDED) continue;
const auto enter = [&](u32 idx, const Position& pos, int depth) {
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 (!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");
// The state evaluate_leaf gives this position on this path.
MoveList legal; MoveList legal;
generate_legal(item.pos, legal); generate_legal(pos, legal);
u64 child_visits = 0; int expected = -1; // not terminal
bool ok = node.first_child >= 2 && node.first_child + node.num_children <= tree_.used() && if (legal.empty()) {
node.num_children == legal.size(); expected = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
for (u32 c = 0; ok && c < node.num_children; c++) { } else if (depth > 0) {
const Node& child = tree_[node.first_child + c]; bool repetition = false;
const Move m = Move::from_raw(child.move); const int n = int(keys.size());
ok = std::find(legal.begin(), legal.end(), m) != legal.end(); for (int back = 4; back <= pos.halfmove && back < n; back += 2)
child_visits += child.visits; if (keys[n - 1 - back] == pos.key) repetition = true;
Position next = item.pos; if (pos.halfmove >= 100 || pos.insufficient_material() || repetition) expected = TERMINAL_DRAW;
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 if (expected >= 0 ? node.state != expected : node.state != UNEXPANDED && node.state != EXPANDED)
// as many visits as its children. fail(idx, pos, "state " + std::to_string(node.state) + " expected " + std::to_string(expected));
const u64 own_visit = item.idx == Tree::root() ? 0 : 1;
if (!ok || node.visits < child_visits + own_visit) { if (node.state != EXPANDED) {
std::cerr << "TREE CORRUPT at node " << item.idx << " (" << item.pos.fen() << ") ok=" << ok if (node.first_edge || node.num_edges) fail(idx, pos, "edges on a node that is not expanded");
<< " visits=" << node.visits << " child_visits=" << child_visits } else {
<< " children=" << int(node.num_children) << " legal=" << legal.size() if (!node.first_edge || node.first_edge + node.num_edges > tree_.edges_used() ||
<< " first=" << node.first_child << " used=" << tree_.used() << std::endl; node.num_edges != legal.size())
std::abort(); fail(idx, pos, "bad edge block, legal moves " + std::to_string(legal.size()));
bool 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() || seen[it - legal.begin()]) fail(idx, pos, "illegal or repeated edge move");
seen[it - legal.begin()] = true;
if (e.draws) fail(idx, pos, "edge with draws");
if (e.child >= tree_.nodes_used()) fail(idx, pos, "edge child out of range");
if (bool(e.child) != bool(e.visits)) fail(idx, pos, "edge child without visits or the reverse");
if (e.child && e.visits != tree_.node(e.child).visits) fail(idx, pos, "edge and child visits differ");
if (e.child && ++in_degree[e.child] != 1) fail(idx, pos, "node reached twice");
edge_visits += e.visits;
}
edges += node.num_edges;
if (node.visits < edge_visits + (idx == tree_.root() ? 0 : 1))
fail(idx, pos, "fewer visits than the edges, edge visits " + std::to_string(edge_visits));
}
stack.push_back({idx, pos, depth});
};
if (tree_.root() == 0 || tree_.root() >= tree_.nodes_used()) fail(tree_.root(), root_pos_, "bad root index");
enter(tree_.root(), root_pos_, 0);
while (!stack.empty()) {
Frame& f = stack.back();
const Node& node = tree_.node(f.idx);
if (f.next < node.num_edges) {
const Edge& e = tree_.edge(node.first_edge + f.next++);
if (!e.child) continue;
Position next = f.pos;
next.make_move(Move::from_raw(e.move));
keys.push_back(next.key);
const int depth = f.depth + 1;
enter(e.child, next, depth); // invalidates f
} else {
stack.pop_back();
if (!stack.empty()) keys.pop_back();
} }
} }
uci_io::send("info string tree verified: " + std::to_string(checked) + " nodes");
if (nodes != tree_.nodes_used() - 1 || edges != tree_.edges_used() - 1)
fail(tree_.root(), root_pos_,
"unreachable nodes or edges: reached " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges");
uci_io::send("info string tree verified: " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges");
} }
#endif #endif
float Searcher::evaluate_leaf(u32 idx, const Position& pos, int depth) { float Searcher::evaluate_leaf(u32 idx, const Position& pos, int depth) {
Node& node = tree_[idx]; Node& node = tree_.node(idx);
MoveList moves; MoveList moves;
generate_legal(pos, moves); generate_legal(pos, moves);
@@ -322,12 +452,10 @@ float Searcher::evaluate_leaf(u32 idx, const Position& pos, int depth) {
} }
bool Searcher::expand(u32 idx, const Position& pos) { bool Searcher::expand(u32 idx, const Position& pos) {
Node& node = tree_[idx];
MoveList moves; MoveList moves;
generate_legal(pos, moves); generate_legal(pos, moves);
const u32 first = tree_.alloc(u32(moves.size())); const u32 first = tree_.alloc_edges(u32(moves.size()));
if (!first) { if (!first) {
// Out of memory: this time the node stays a leaf; the tree is collected // 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. // right after this playout, so the next visit can expand it.
@@ -345,47 +473,49 @@ bool Searcher::expand(u32 idx, const Position& pos) {
eval::policy(pos, moves, params.policy_temperature, bias, priors); eval::policy(pos, moves, params.policy_temperature, bias, priors);
for (int i = 0; i < moves.size(); i++) { for (int i = 0; i < moves.size(); i++) {
Node& child = tree_[first + i]; Edge& e = tree_.edge(first + u32(i));
child = Node{}; e = Edge{};
child.move = moves[i].raw(); e.move = moves[i].raw();
child.policy = u16(std::lround(std::clamp(priors[i], 0.0f, 1.0f) * 65535.0f)); e.policy = u16(std::lround(std::clamp(priors[i], 0.0f, 1.0f) * 65535.0f));
} }
node.first_child = first; Node& node = tree_.node(idx);
node.num_children = u8(moves.size()); node.first_edge = first;
node.num_edges = u8(moves.size());
node.state = EXPANDED; node.state = EXPANDED;
return true; return true;
} }
u32 Searcher::select_child(u32 idx) const { u32 Searcher::select_edge(u32 idx) const {
const Node& node = tree_[idx]; const Node& node = tree_.node(idx);
// node.q is from the view of the side that moved into this node, so the side // node.q is from the view of the side that moved into this node, so the side
// to move here sees -q. // to move here sees -q.
const float parent_q = node.visits ? -node.q : 0.0f; const float parent_q = node.visits ? -node.q : 0.0f;
float visited_policy = 0.0f; float visited_policy = 0.0f;
for (u32 i = 0; i < node.num_children; i++) { for (u32 i = 0; i < node.num_edges; i++) {
const Node& child = tree_[node.first_child + i]; const Edge& e = tree_.edge(node.first_edge + i);
if (child.visits) visited_policy += child.prior(); if (e.visits) visited_policy += e.prior();
} }
const float fpu = parent_q - params.fpu_reduction * std::sqrt(visited_policy); const float fpu = parent_q - params.fpu_reduction * std::sqrt(visited_policy);
// Exploration grows with the visits (Monty's scaling): a node searched a // Exploration grows with the visits (Monty's scaling): a node searched a
// lot keeps giving its other children a chance. // lot keeps giving its other moves a chance.
const float n = float(std::max<u32>(node.visits, 1)); const float n = float(std::max<u32>(node.visits, 1));
// The root, where the move is chosen, explores more. // The root, where the move is chosen, explores more.
const float base_cpuct = idx == Tree::root() ? params.root_cpuct : params.cpuct; 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 cpuct = base_cpuct * (1.0f + std::log((n + params.cpuct_visit_scale) / params.cpuct_visit_scale));
const float explore = cpuct * std::sqrt(n); const float explore = cpuct * std::sqrt(n);
u32 best = node.first_child; u32 best = node.first_edge;
float best_score = -1e30f; float best_score = -1e30f;
for (u32 i = 0; i < node.num_children; i++) { for (u32 i = 0; i < node.num_edges; i++) {
const u32 c = node.first_child + i; const u32 c = node.first_edge + i;
const Node& child = tree_[c]; const Edge& e = tree_.edge(c);
const float q = child.visits ? child.q : fpu; // The child's Q is from the view of the side to move here.
const float score = q + explore * child.prior() / float(1 + child.visits); const float q = e.visits ? tree_.node(e.child).q : fpu;
const float score = q + explore * e.prior() / float(1 + e.visits);
if (score > best_score) { if (score > best_score) {
best_score = score; best_score = score;
best = c; best = c;
@@ -398,14 +528,15 @@ void Searcher::playout() {
Position pos = root_pos_; Position pos = root_pos_;
history_.resize(root_history_size_); history_.resize(root_history_size_);
path_.clear(); path_.clear();
edge_path_.clear();
u32 idx = Tree::root(); u32 idx = tree_.root();
path_.push_back(idx); path_.push_back(idx);
int depth = 0; int depth = 0;
float value; float value;
for (;;) { for (;;) {
const Node& node = tree_[idx]; const Node& node = tree_.node(idx);
if (node.state == TERMINAL_LOSS) { if (node.state == TERMINAL_LOSS) {
value = -1.0f; value = -1.0f;
break; break;
@@ -416,7 +547,7 @@ void Searcher::playout() {
} }
if (node.state == UNEXPANDED) { if (node.state == UNEXPANDED) {
// Most leaves are only ever visited once, so a first visit just // Most leaves are only ever visited once, so a first visit just
// evaluates; children (moves, priors, memory) come on the second. // evaluates; edges (moves, priors, memory) come on the second.
if (node.visits == 0) { if (node.visits == 0) {
value = evaluate_leaf(idx, pos, depth); value = evaluate_leaf(idx, pos, depth);
break; break;
@@ -427,10 +558,34 @@ void Searcher::playout() {
} }
} }
idx = select_child(idx); const u32 e = select_edge(idx);
pos.make_move(Move::from_raw(tree_[idx].move)); Edge& edge = tree_.edge(e);
u32 child = edge.child;
const bool created = !child;
if (created) {
// The first time this move is chosen: its node is created now and
// evaluated on this visit.
child = tree_.alloc_node();
if (!child) {
// The node arena is full: as when expansion fails, this node
// takes the playout and the tree is collected right after.
gc_pending_ = true;
value = eval::value(pos);
break;
}
edge.child = child;
}
pos.make_move(Move::from_raw(edge.move));
if (created) {
Node& fresh = tree_.node(child);
fresh = Node{};
fresh.key = pos.key;
fresh.check = position_check(pos);
}
history_.push_back(pos.key); history_.push_back(pos.key);
path_.push_back(idx); path_.push_back(child);
edge_path_.push_back(e);
idx = child;
depth++; depth++;
} }
@@ -438,18 +593,22 @@ void Searcher::playout() {
// the view of the side that moved into it, so flip before every update. // the view of the side that moved into it, so flip before every update.
// The same result in centipawns scores the move into each node in the // The same result in centipawns scores the move into each node in the
// butterfly history, for the side that played it (the side to move at the // butterfly history, for the side that played it (the side to move at the
// parent, depth i - 1). // parent, depth i - 1). Edge visits are kept equal to the child's.
int bonus = eval::q_to_cp(std::clamp(value, -0.998f, 0.998f)); int bonus = eval::q_to_cp(std::clamp(value, -0.998f, 0.998f));
for (size_t i = path_.size(); i-- > 0;) { for (size_t i = path_.size(); i-- > 0;) {
value = -value; value = -value;
bonus = -bonus; bonus = -bonus;
Node& node = tree_[path_[i]]; Node& node = tree_.node(path_[i]);
node.visits++; node.visits++;
node.q += (value - node.q) / float(node.visits); node.q += (value - node.q) / float(node.visits);
// The Q from the view of the side to move at the node. Draws by // The Q from the view of the side to move at the node. Draws by
// repetition or the 50-move rule belong to the path, not the position. // repetition or the 50-move rule belong to the path, not the position.
if (node.state != TERMINAL_DRAW) value_hash_.store(history_[root_history_size_ - 1 + i], -node.q, node.visits); if (node.state != TERMINAL_DRAW) value_hash_.store(history_[root_history_size_ - 1 + i], -node.q, node.visits);
if (i) butterfly_.update(root_pos_.stm ^ int((i - 1) & 1), Move::from_raw(node.move), bonus); if (i) {
Edge& e = tree_.edge(edge_path_[i - 1]);
e.visits++;
butterfly_.update(root_pos_.stm ^ int((i - 1) & 1), Move::from_raw(e.move), bonus);
}
} }
iterations_++; iterations_++;
@@ -457,36 +616,37 @@ void Searcher::playout() {
seldepth_ = std::max(seldepth_, depth); seldepth_ = std::max(seldepth_, depth);
} }
u32 Searcher::best_child(u32 idx) const { u32 Searcher::best_edge(u32 idx) const {
const Node& node = tree_[idx]; const Node& node = tree_.node(idx);
u32 best = 0; u32 best = 0;
for (u32 i = 0; i < node.num_children; i++) { for (u32 i = 0; i < node.num_edges; i++) {
const u32 c = node.first_child + i; const u32 c = node.first_edge + i;
if (!best) { if (!best) {
best = c; best = c;
continue; continue;
} }
const Node& a = tree_[c]; const Edge& a = tree_.edge(c);
const Node& b = tree_[best]; const Edge& b = tree_.edge(best);
// Most visits wins; ties go to the better Q, then to the higher prior. // 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; 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; return best;
} }
void Searcher::print_info() const { void Searcher::print_info() const {
const Node& root = tree_[Tree::root()]; const Node& root = tree_.node(tree_.root());
const i64 ms = elapsed_ms(); const i64 ms = elapsed_ms();
const u32 best = best_child(Tree::root()); const u32 best = best_edge(tree_.root());
std::ostringstream out; std::ostringstream out;
out << "info depth " << (iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0) << " seldepth " out << "info depth " << (iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0) << " seldepth "
<< seldepth_; << seldepth_;
const float q = best && tree_[best].visits ? tree_[best].q : -root.q; const float q = best && tree_.edge(best).visits ? edge_q(tree_.edge(best)) : -root.q;
out << " score cp " << eval::q_to_cp(q); out << " score cp " << eval::q_to_cp(q);
out << " nodes " << iterations_ << " nps " << (ms ? iterations_ * 1000 / u64(ms) : iterations_) << " time " << ms; out << " nodes " << iterations_ << " nps " << (ms ? iterations_ * 1000 / u64(ms) : iterations_) << " time " << ms;
out << " hashfull " << (tree_.used() * 1000 / tree_.capacity()); out << " hashfull " << tree_.fill_permille();
out << " pv"; out << " pv";
for (const Move m : principal_variation()) out << ' ' << root_pos_.uci(m); for (const Move m : principal_variation()) out << ' ' << root_pos_.uci(m);
@@ -495,19 +655,19 @@ void Searcher::print_info() const {
std::vector<Move> Searcher::principal_variation() const { std::vector<Move> Searcher::principal_variation() const {
std::vector<Move> pv; std::vector<Move> pv;
u32 idx = Tree::root(); u32 idx = tree_.root();
for (int ply = 0; ply < 64; ply++) { for (int ply = 0; ply < 64; ply++) {
const u32 c = best_child(idx); const u32 c = best_edge(idx);
if (!c || !tree_[c].visits) break; if (!c || !tree_.edge(c).visits) break;
pv.push_back(Move::from_raw(tree_[c].move)); pv.push_back(Move::from_raw(tree_.edge(c).move));
idx = c; idx = tree_.edge(c).child;
} }
return pv; return pv;
} }
void Searcher::draw_dashboard(bool done) { void Searcher::draw_dashboard(bool done) {
const Node& root = tree_[Tree::root()]; const Node& root = tree_.node(tree_.root());
const u32 best = best_child(Tree::root()); const u32 best = best_edge(tree_.root());
const i64 ms = elapsed_ms(); const i64 ms = elapsed_ms();
pretty::Dashboard d; pretty::Dashboard d;
@@ -519,12 +679,12 @@ void Searcher::draw_dashboard(bool done) {
d.ms = ms; d.ms = ms;
d.time_limit_ms = time_limit_ms_; d.time_limit_ms = time_limit_ms_;
d.node_limit = node_limit_; d.node_limit = node_limit_;
d.hashfull = int(tree_.used() * 1000 / tree_.capacity()); d.hashfull = tree_.fill_permille();
d.cp = eval::q_to_cp(best && tree_[best].visits ? tree_[best].q : -root.q); d.cp = eval::q_to_cp(best && tree_.edge(best).visits ? edge_q(tree_.edge(best)) : -root.q);
d.pv = principal_variation(); d.pv = principal_variation();
for (u32 i = 0; i < root.num_children; i++) { for (u32 i = 0; i < root.num_edges; i++) {
const Node& child = tree_[root.first_child + i]; const Edge& e = tree_.edge(root.first_edge + i);
d.moves.push_back({Move::from_raw(child.move), child.visits, eval::q_to_cp(child.q), child.prior()}); d.moves.push_back({Move::from_raw(e.move), e.visits, eval::q_to_cp(edge_q(e)), e.prior()});
} }
d.reused = reused_; d.reused = reused_;
d.collections = gc_runs_; d.collections = gc_runs_;
@@ -544,14 +704,14 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
// Check the previous tree as the last search left it, and again after rerooting. // Check the previous tree as the last search left it, and again after rerooting.
if (tree_valid_ && history_.size() >= prev_history_.size()) { if (tree_valid_ && history_.size() >= prev_history_.size()) {
root_pos_ = prev_root_; root_pos_ = prev_root_;
verify_tree(); verify_tree(prev_history_);
root_pos_ = root; root_pos_ = root;
} }
#endif #endif
const size_t reused = reuse_tree(root); const size_t reused = reuse_tree(root);
if (!reused) tree_.clear(); if (!reused) clear_tree(root);
#ifdef RIGBY_VERIFY_TREE #ifdef RIGBY_VERIFY_TREE
if (reused) verify_tree(); if (reused) verify_tree(history_);
#endif #endif
if (print && !pretty && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes"); if (print && !pretty && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes");
iterations_ = 0; iterations_ = 0;
@@ -580,18 +740,18 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
// The root needs its children before the first playout, so that even a // The root needs its children before the first playout, so that even a
// single playout leaves a move to play. // single playout leaves a move to play.
if (tree_[Tree::root()].state == UNEXPANDED && !expand(Tree::root(), root)) { if (tree_.node(tree_.root()).state == UNEXPANDED && !expand(tree_.root(), root)) {
tree_.clear(); clear_tree(root);
gc_pending_ = false; gc_pending_ = false;
expand(Tree::root(), root); expand(tree_.root(), root);
} }
// Root move visits brought along by tree reuse, for smart pruning. The // Root move visits brought along by tree reuse, for smart pruning. The
// root's children keep their order through collections. // root's edges keep their order through collections.
root_start_visits_.clear(); root_start_visits_.clear();
{ {
const Node& r = tree_[Tree::root()]; const Node& r = tree_.node(tree_.root());
for (u32 i = 0; i < r.num_children; i++) root_start_visits_.push_back(tree_[r.first_child + i].visits); 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 // UCI reports once a second; the dashboard for a human is redrawn in place
@@ -606,7 +766,7 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
gc_pending_ = false; gc_pending_ = false;
gc_runs_++; gc_runs_++;
#ifdef RIGBY_VERIFY_TREE #ifdef RIGBY_VERIFY_TREE
verify_tree(); verify_tree(std::vector<u64>(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)));
#endif #endif
} }
if (print && (iterations_ & info_mask) == 0) { if (print && (iterations_ & info_mask) == 0) {
@@ -626,8 +786,11 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
if (gc_runs_) uci_io::send("info string tree collected " + std::to_string(gc_runs_) + " times"); if (gc_runs_) uci_io::send("info string tree collected " + std::to_string(gc_runs_) + " times");
} }
const u32 best = best_child(Tree::root()); #ifdef RIGBY_VERIFY_TREE
result.best = Move::from_raw(tree_[best].move); 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.nodes = iterations_;
result.tree_positions = iterations_ + depth_sum_; result.tree_positions = iterations_ + depth_sum_;
result.time_ms = elapsed_ms(); result.time_ms = elapsed_ms();
+85 -29
View File
@@ -19,48 +19,93 @@ enum NodeState : u8 {
TERMINAL_DRAW, TERMINAL_DRAW,
}; };
// 20 bytes. Children of a node sit next to each other in the arena, so a node // A move out of a node. A node's edges sit next to each other in the edge
// only needs the index of its first child. // arena, so the node only needs the index of the first one. The child node is
struct Node { // created the first time search selects the edge.
u32 first_child = 0; struct Edge {
u32 visits = 0; u32 child = 0; // node index, 0 = no node yet
float q = 0.0f; // running mean, from the view of the side that played `move` u32 visits = 0; // how often search chose this move here (equals the child's visits in a tree)
u32 draws = 0; // of those, playouts that ended in a draw of the path (unused while the search is a tree)
u16 move = 0; u16 move = 0;
u16 policy = 0; // prior scaled to 0..65535 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); } float prior() const { return float(policy) * (1.0f / 65535.0f); }
}; };
static_assert(sizeof(Edge) == 16);
// A position, created when search first reaches it.
struct Node {
u64 key = 0; // Zobrist key of the position
u32 first_edge = 0; // 0 = not expanded
u32 visits = 0;
float q = 0.0f; // running mean, from the view of the side that moved into the node
// `u` and `base` are set by garbage collection (the Q and visits a pruned
// node keeps) but not read yet. `check` is a second fingerprint of the
// position (see position_check). All three are for graph search.
float u = 0.0f;
u32 base = 0;
u8 num_edges = 0;
u8 state = UNEXPANDED;
u16 check = 0;
};
static_assert(sizeof(Node) == 32);
// A 16-bit fingerprint of the position that does not depend on the Zobrist keys.
u16 position_check(const Position& pos);
// Two arenas: nodes and edges. Index 0 of each is null.
class Tree { class Tree {
public: public:
// Edges per node the arenas are sized for. Measured in step 1 of the MCGS
// plan (docs/mcgs-log.md, edges per visited node): 13 on average in 5 s
// searches without collections, 19-21 in middlegames, 3.6-5.5 in simple
// endgames, and 3-9 right after collections (pruned nodes keep their node
// but lose their edges). See set_hash for the choice.
static constexpr size_t EDGES_PER_NODE = 8;
void resize_bytes(size_t bytes); void resize_bytes(size_t bytes);
void clear(); void clear();
// Returns the index of `count` fresh nodes, or 0 when the arena is full. // A fresh node, or 0 when the node arena is full.
u32 alloc(u32 count); u32 alloc_node();
// Makes `new_root` the root and packs its subtree to the front of the arena; // The index of `count` fresh edges, or 0 when the edge arena is full.
// everything else is dropped. Returns the number of nodes kept. u32 alloc_edges(u32 count);
// Makes `new_root` the root and packs its subtree to the front of the
// arenas; everything else is dropped. Returns the number of nodes kept.
size_t reroot(u32 new_root); size_t reroot(u32 new_root);
// Frees memory when the arena is full: the least visited parts of the tree // Frees memory when an arena is full: the least visited parts of the tree
// are cut back to leaves until at most `keep_fraction` of it is in use. // are cut back to leaves until at most `keep_fraction` of each arena is in
// use. Returns the number of nodes kept.
size_t collect_garbage(double keep_fraction); size_t collect_garbage(double keep_fraction);
// The same with explicit targets (in slots, null slots included).
size_t collect_garbage(size_t node_target, size_t edge_target);
Node& operator[](u32 idx) { return nodes_[idx]; } Node& node(u32 idx) { return nodes_[idx]; }
const Node& operator[](u32 idx) const { return nodes_[idx]; } const Node& node(u32 idx) const { return nodes_[idx]; }
static constexpr u32 root() { return 1; } Edge& edge(u32 idx) { return edges_[idx]; }
const Edge& edge(u32 idx) const { return edges_[idx]; }
u32 root() const { return root_; }
size_t used() const { return used_; } size_t nodes_used() const { return nodes_used_; }
size_t capacity() const { return nodes_.size(); } size_t edges_used() const { return edges_used_; }
size_t node_capacity() const { return nodes_.size(); }
size_t edge_capacity() const { return edges_.size(); }
// How full the fuller arena is, per mille.
int fill_permille() const {
return int(std::max(nodes_used_ * 1000 / nodes_.size(), edges_used_ * 1000 / edges_.size()));
}
private: private:
std::vector<Node> nodes_; std::vector<Node> nodes_;
size_t used_ = 0; std::vector<Edge> edges_;
size_t nodes_used_ = 0;
size_t edges_used_ = 0;
u32 root_ = 1;
// Keeps the subtree of `new_root`, dropping the children of every node with // Keeps what is reachable from `new_root`, dropping the edges of every
// fewer than `min_visits` visits, and packs it to the front in place. // node with fewer than `min_visits` visits, and packs both arenas to the
// front in place.
size_t compact(u32 new_root, u32 min_visits); size_t compact(u32 new_root, u32 min_visits);
u32 prune_threshold(size_t target) const; u32 prune_threshold(size_t node_target, size_t edge_target) const;
}; };
// Butterfly history for MCTS (after Vine, aronpetkovski.com/blog/butterfly-history-mcts): // Butterfly history for MCTS (after Vine, aronpetkovski.com/blog/butterfly-history-mcts):
@@ -160,7 +205,8 @@ public:
Searcher(); Searcher();
void set_hash(size_t mb) { void set_hash(size_t mb) {
// A 32nd of the memory goes to the value hash, the rest to the tree. // A 32nd of the memory goes to the value hash, the rest to the tree
// (split between its arenas by Tree::EDGES_PER_NODE).
const size_t bytes = mb * 1024 * 1024; const size_t bytes = mb * 1024 * 1024;
value_hash_.resize(bytes / 32 / ValueHash::ENTRY_BYTES); value_hash_.resize(bytes / 32 / ValueHash::ENTRY_BYTES);
tree_.resize_bytes(bytes - bytes / 32); tree_.resize_bytes(bytes - bytes / 32);
@@ -189,7 +235,10 @@ private:
ValueHash value_hash_; ValueHash value_hash_;
std::vector<u64> history_; std::vector<u64> history_;
size_t root_history_size_ = 0; size_t root_history_size_ = 0;
// The nodes of a playout, from the root, and the edges between them
// (edge_path_[i] leads from path_[i] to path_[i + 1]).
std::vector<u32> path_; std::vector<u32> path_;
std::vector<u32> edge_path_;
// The previous search, kept so its tree can be reused. // The previous search, kept so its tree can be reused.
bool tree_valid_ = false; bool tree_valid_ = false;
@@ -220,16 +269,20 @@ private:
void playout(); void playout();
// First visit of a node: settles terminal states, otherwise evaluates. // First visit of a node: settles terminal states, otherwise evaluates.
float evaluate_leaf(u32 idx, const Position& pos, int depth); float evaluate_leaf(u32 idx, const Position& pos, int depth);
// Second visit: creates the children with their priors. False when the // Second visit: creates the edges with their priors. False when the
// arena is full (a collection is then scheduled). // arena is full (a collection is then scheduled).
bool expand(u32 idx, const Position& pos); bool expand(u32 idx, const Position& pos);
u32 select_child(u32 idx) const; // The edge PUCT picks at node `idx`.
u32 select_edge(u32 idx) const;
bool is_repetition(const Position& pos) const; bool is_repetition(const Position& pos) const;
// Finds the node for `root` in the previous tree and makes it the root. // 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. // Returns the number of nodes kept, 0 when nothing could be reused.
size_t reuse_tree(const Position& root); size_t reuse_tree(const Position& root);
// Empties the tree, leaving an unexpanded root for `root`.
void clear_tree(const Position& root);
#ifdef RIGBY_VERIFY_TREE #ifdef RIGBY_VERIFY_TREE
void verify_tree() const; // Checks the tree from root_pos_; `history` ends with the root's key.
void verify_tree(const std::vector<u64>& history) const;
#endif #endif
void compute_time_limit(const SearchLimits& limits); void compute_time_limit(const SearchLimits& limits);
@@ -237,7 +290,10 @@ private:
bool should_stop(const SearchLimits& limits) const; bool should_stop(const SearchLimits& limits) const;
bool best_move_settled(i64 ms, i64 limit_ms) const; bool best_move_settled(i64 ms, i64 limit_ms) const;
u32 best_child(u32 idx) const; // The edge with the most visits at node `idx`, 0 when it has none.
u32 best_edge(u32 idx) const;
// Q of an edge from the view of the side choosing it (0 when unvisited).
float edge_q(const Edge& e) const { return e.visits ? tree_.node(e.child).q : 0.0f; }
void print_info() const; void print_info() const;
std::vector<Move> principal_variation() const; std::vector<Move> principal_variation() const;
void draw_dashboard(bool done); void draw_dashboard(bool done);