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 <algorithm>
#include <bit>
#include <cmath>
#include <cstring>
#include <iostream>
@@ -16,113 +17,166 @@ 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) {
const size_t count = std::max<size_t>(bytes / sizeof(Node), 1024);
nodes_.assign(count, Node{});
// A node costs its own 32 bytes plus EDGES_PER_NODE edges of 16.
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();
edges_.assign(node_count * EDGES_PER_NODE, Edge{});
edges_.shrink_to_fit();
clear();
}
void Tree::clear() {
used_ = 2; // index 0 is the null child, index 1 is the root
nodes_[root()] = Node{};
nodes_used_ = 2; // index 0 is the null node, index 1 the root
edges_used_ = 1; // index 0 is the null edge
root_ = 1;
nodes_[root_] = Node{};
}
u32 Tree::alloc(u32 count) {
if (used_ + count > nodes_.size()) return 0;
const u32 idx = u32(used_);
used_ += count;
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) {
if (new_root == root()) return used_;
if (new_root == root_) return nodes_used_ - 1;
return compact(new_root, 0);
}
size_t Tree::collect_garbage(double keep_fraction) {
const size_t target = size_t(double(nodes_.size()) * keep_fraction);
return compact(root(), prune_threshold(target));
return collect_garbage(size_t(double(nodes_.size()) * keep_fraction), size_t(double(edges_.size()) * keep_fraction));
}
u32 Tree::prune_threshold(size_t target) const {
// A node's children survive a collection with threshold T when the node has
// 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.
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 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;
std::vector<u64> edges_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()) {
const Node& node = nodes_[stack.back()];
stack.pop_back();
if (!node.first_child) continue;
children_by_visits[std::min(node.visits, CAP)] += node.num_children;
for (u32 i = 0; i < node.num_children; i++) stack.push_back(node.first_child + i);
if (!node.first_edge) continue;
const u32 bucket = std::min(node.visits, CAP);
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--) {
if (kept + children_by_visits[v] > target) return v + 1;
kept += children_by_visits[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) {
// Every child block that stays, as (old first index, size). Nodes below the
// visit threshold lose their children and become leaves again; they keep
// their visits and Q, and get expanded anew if search comes back to them.
// 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 (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<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_child) continue;
if (!node.first_edge) continue;
if (idx != new_root && node.visits < min_visits) {
node.first_child = 0;
node.num_children = 0;
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_child, node.num_children);
for (u32 i = 0; i < node.num_children; i++) stack.push_back(node.first_child + i);
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);
}
}
}
// 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.
// 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 = 2;
u32 next_edge = 1;
for (size_t i = 0; i < blocks.size(); i++) {
dest[i] = next;
next += blocks[i].second;
dest[i] = next_edge;
next_edge += blocks[i].second;
}
const auto remap = [&](u32 old_first) -> u32 {
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())];
};
// 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 (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(&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++) {
Node& node = nodes_[dest[i] + j];
node.first_child = remap(node.first_child);
Edge& e = edges_[dest[i] + j];
e.child = forward[e.child];
}
}
nodes_[root()] = new_root_node;
used_ = next;
return used_ - 1; // everything but the null slot
root_ = forward[new_root];
nodes_used_ = next_node;
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); }
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 {
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
// at once. The move leading this search must also be the one played.
if (ms <= 0 || iterations_ < 256) return false;
const Node& root = tree_[Tree::root()];
if (root_start_visits_.size() != root.num_children) 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_children; i++) {
const u32 v = tree_[root.first_child + i].visits - root_start_visits_[i];
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_child + i;
leader = root.first_edge + i;
} else if (v > second) {
second = v;
}
}
if (leader != best_child(Tree::root())) return false;
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);
@@ -225,18 +286,21 @@ size_t Searcher::reuse_tree(const Position& root) {
!std::equal(prev_history_.begin(), prev_history_.end(), history_.begin()))
return 0;
u32 idx = Tree::root();
u32 idx = tree_.root();
Position pos = prev_root_;
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;
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;
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]) {
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;
}
}
@@ -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
// 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);
}
#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 {
// Debug check, from the root as `root_pos_` with the game history `history`
// (ending with the root's key):
// - every node is reached exactly once (in-degree 1, the root 0), and the
// arenas hold nothing else;
// - 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;
Position pos;
int depth;
u32 next = 0;
};
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;
std::vector<Frame> stack;
u64 nodes = 0, edges = 0;
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;
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});
generate_legal(pos, legal);
int expected = -1; // not terminal
if (legal.empty()) {
expected = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
} else if (depth > 0) {
bool repetition = false;
const int n = int(keys.size());
for (int back = 4; back <= pos.halfmove && back < n; back += 2)
if (keys[n - 1 - back] == pos.key) repetition = true;
if (pos.halfmove >= 100 || pos.insufficient_material() || repetition) expected = TERMINAL_DRAW;
}
// 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();
if (expected >= 0 ? node.state != expected : node.state != UNEXPANDED && node.state != EXPANDED)
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");
} else {
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 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
float Searcher::evaluate_leaf(u32 idx, const Position& pos, int depth) {
Node& node = tree_[idx];
Node& node = tree_.node(idx);
MoveList 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) {
Node& node = tree_[idx];
MoveList moves;
generate_legal(pos, moves);
const u32 first = tree_.alloc(u32(moves.size()));
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.
@@ -345,47 +473,49 @@ bool Searcher::expand(u32 idx, const Position& pos) {
eval::policy(pos, moves, params.policy_temperature, bias, 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));
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.first_child = first;
node.num_children = u8(moves.size());
Node& node = tree_.node(idx);
node.first_edge = first;
node.num_edges = u8(moves.size());
node.state = EXPANDED;
return true;
}
u32 Searcher::select_child(u32 idx) const {
const Node& node = tree_[idx];
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.
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();
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 children a chance.
// 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 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_child;
u32 best = node.first_edge;
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);
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 ? tree_.node(e.child).q : fpu;
const float score = q + explore * e.prior() / float(1 + e.visits);
if (score > best_score) {
best_score = score;
best = c;
@@ -398,14 +528,15 @@ void Searcher::playout() {
Position pos = root_pos_;
history_.resize(root_history_size_);
path_.clear();
edge_path_.clear();
u32 idx = Tree::root();
u32 idx = tree_.root();
path_.push_back(idx);
int depth = 0;
float value;
for (;;) {
const Node& node = tree_[idx];
const Node& node = tree_.node(idx);
if (node.state == TERMINAL_LOSS) {
value = -1.0f;
break;
@@ -416,7 +547,7 @@ void Searcher::playout() {
}
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.
// evaluates; edges (moves, priors, memory) come on the second.
if (node.visits == 0) {
value = evaluate_leaf(idx, pos, depth);
break;
@@ -427,10 +558,34 @@ void Searcher::playout() {
}
}
idx = select_child(idx);
pos.make_move(Move::from_raw(tree_[idx].move));
const u32 e = select_edge(idx);
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);
path_.push_back(idx);
path_.push_back(child);
edge_path_.push_back(e);
idx = child;
depth++;
}
@@ -438,18 +593,22 @@ void Searcher::playout() {
// 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
// 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));
for (size_t i = path_.size(); i-- > 0;) {
value = -value;
bonus = -bonus;
Node& node = tree_[path_[i]];
Node& node = tree_.node(path_[i]);
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
// 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 (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_++;
@@ -457,36 +616,37 @@ void Searcher::playout() {
seldepth_ = std::max(seldepth_, depth);
}
u32 Searcher::best_child(u32 idx) const {
const Node& node = tree_[idx];
u32 Searcher::best_edge(u32 idx) const {
const Node& node = tree_.node(idx);
u32 best = 0;
for (u32 i = 0; i < node.num_children; i++) {
const u32 c = node.first_child + i;
for (u32 i = 0; i < node.num_edges; i++) {
const u32 c = node.first_edge + i;
if (!best) {
best = c;
continue;
}
const Node& a = tree_[c];
const Node& b = tree_[best];
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 ? 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;
}
void Searcher::print_info() const {
const Node& root = tree_[Tree::root()];
const Node& root = tree_.node(tree_.root());
const i64 ms = elapsed_ms();
const u32 best = best_child(Tree::root());
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_[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 << " 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";
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> pv;
u32 idx = Tree::root();
u32 idx = tree_.root();
for (int ply = 0; ply < 64; ply++) {
const u32 c = best_child(idx);
if (!c || !tree_[c].visits) break;
pv.push_back(Move::from_raw(tree_[c].move));
idx = c;
const u32 c = best_edge(idx);
if (!c || !tree_.edge(c).visits) break;
pv.push_back(Move::from_raw(tree_.edge(c).move));
idx = tree_.edge(c).child;
}
return pv;
}
void Searcher::draw_dashboard(bool done) {
const Node& root = tree_[Tree::root()];
const u32 best = best_child(Tree::root());
const Node& root = tree_.node(tree_.root());
const u32 best = best_edge(tree_.root());
const i64 ms = elapsed_ms();
pretty::Dashboard d;
@@ -519,12 +679,12 @@ void Searcher::draw_dashboard(bool done) {
d.ms = ms;
d.time_limit_ms = time_limit_ms_;
d.node_limit = node_limit_;
d.hashfull = int(tree_.used() * 1000 / tree_.capacity());
d.cp = eval::q_to_cp(best && tree_[best].visits ? tree_[best].q : -root.q);
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_children; i++) {
const Node& child = tree_[root.first_child + i];
d.moves.push_back({Move::from_raw(child.move), child.visits, eval::q_to_cp(child.q), child.prior()});
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_;
@@ -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.
if (tree_valid_ && history_.size() >= prev_history_.size()) {
root_pos_ = prev_root_;
verify_tree();
verify_tree(prev_history_);
root_pos_ = root;
}
#endif
const size_t reused = reuse_tree(root);
if (!reused) tree_.clear();
if (!reused) clear_tree(root);
#ifdef RIGBY_VERIFY_TREE
if (reused) 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;
@@ -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
// single playout leaves a move to play.
if (tree_[Tree::root()].state == UNEXPANDED && !expand(Tree::root(), root)) {
tree_.clear();
if (tree_.node(tree_.root()).state == UNEXPANDED && !expand(tree_.root(), root)) {
clear_tree(root);
gc_pending_ = false;
expand(Tree::root(), root);
expand(tree_.root(), root);
}
// 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();
{
const Node& r = tree_[Tree::root()];
for (u32 i = 0; i < r.num_children; i++) root_start_visits_.push_back(tree_[r.first_child + i].visits);
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
@@ -606,7 +766,7 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
gc_pending_ = false;
gc_runs_++;
#ifdef RIGBY_VERIFY_TREE
verify_tree();
verify_tree(std::vector<u64>(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)));
#endif
}
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");
}
const u32 best = best_child(Tree::root());
result.best = Move::from_raw(tree_[best].move);
#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();
+85 -29
View File
@@ -19,48 +19,93 @@ enum NodeState : u8 {
TERMINAL_DRAW,
};
// 20 bytes. Children of a node sit next to each other in the arena, so a node
// only needs the index of its first child.
struct Node {
u32 first_child = 0;
u32 visits = 0;
float q = 0.0f; // running mean, from the view of the side that played `move`
// A move out of a node. A node's edges sit next to each other in the edge
// arena, so the node only needs the index of the first one. The child node is
// created the first time search selects the edge.
struct Edge {
u32 child = 0; // node index, 0 = no node yet
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 policy = 0; // prior scaled to 0..65535
u8 num_children = 0;
u8 state = UNEXPANDED;
u16 policy = 0; // prior scaled to 0..65535
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 {
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 clear();
// Returns the index of `count` fresh nodes, or 0 when the arena is full.
u32 alloc(u32 count);
// Makes `new_root` the root and packs its subtree to the front of the arena;
// everything else is dropped. Returns the number of nodes kept.
// A fresh node, or 0 when the node arena is full.
u32 alloc_node();
// The index of `count` fresh edges, or 0 when the edge arena is full.
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);
// Frees memory when the 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.
// 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 each arena is in
// use. Returns the number of nodes kept.
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]; }
const Node& operator[](u32 idx) const { return nodes_[idx]; }
static constexpr u32 root() { return 1; }
Node& node(u32 idx) { return nodes_[idx]; }
const Node& node(u32 idx) const { return nodes_[idx]; }
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 capacity() const { return nodes_.size(); }
size_t nodes_used() const { return nodes_used_; }
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:
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
// fewer than `min_visits` visits, and packs it to the front in place.
// Keeps what is reachable from `new_root`, dropping the edges of every
// 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);
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):
@@ -160,7 +205,8 @@ public:
Searcher();
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;
value_hash_.resize(bytes / 32 / ValueHash::ENTRY_BYTES);
tree_.resize_bytes(bytes - bytes / 32);
@@ -189,7 +235,10 @@ private:
ValueHash value_hash_;
std::vector<u64> history_;
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> edge_path_;
// The previous search, kept so its tree can be reused.
bool tree_valid_ = false;
@@ -220,16 +269,20 @@ private:
void playout();
// First visit of a node: settles terminal states, otherwise evaluates.
float evaluate_leaf(u32 idx, const Position& pos, int depth);
// Second visit: creates the children with their priors. False when the
// Second visit: creates the edges with their priors. False when the
// arena is full (a collection is then scheduled).
bool expand(u32 idx, const Position& pos);
u32 select_child(u32 idx) const;
// The edge PUCT picks at node `idx`.
u32 select_edge(u32 idx) const;
bool is_repetition(const Position& pos) const;
// Finds the node for `root` in the previous tree and makes it the root.
// Returns the number of nodes kept, 0 when nothing could be reused.
size_t reuse_tree(const Position& root);
// Empties the tree, leaving an unexpanded root for `root`.
void clear_tree(const Position& root);
#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
void compute_time_limit(const SearchLimits& limits);
@@ -237,7 +290,10 @@ private:
bool should_stop(const SearchLimits& limits) 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;
std::vector<Move> principal_variation() const;
void draw_dashboard(bool done);