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 447 additions and 244 deletions
Showing only changes of commit 6ec8769555 - Show all commits

No files matched your search

+354 -212
View File
@@ -29,21 +29,68 @@ u16 position_check(const Position& pos) {
} }
void Tree::resize_bytes(size_t bytes) { void Tree::resize_bytes(size_t bytes) {
// A node costs its own 32 bytes plus EDGES_PER_NODE edges of 16. // A node costs its own 32 bytes, EDGES_PER_NODE edges of 16 and at least
const size_t per_node = sizeof(Node) + EDGES_PER_NODE * sizeof(Edge); // two table slots of 8. The table's size is a power of two of at least
const size_t node_count = std::max<size_t>(bytes / per_node, 1024); // 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_.assign(node_count, Node{});
nodes_.shrink_to_fit(); nodes_.shrink_to_fit();
edges_.assign(node_count * EDGES_PER_NODE, Edge{}); edges_.assign(node_count * EDGES_PER_NODE, Edge{});
edges_.shrink_to_fit(); edges_.shrink_to_fit();
table_.assign(slots, Slot{});
table_.shrink_to_fit();
table_mask_ = slots - 1;
clear(); clear();
} }
void Tree::clear() { void Tree::clear() {
nodes_used_ = 2; // index 0 is the null node, index 1 the root nodes_used_ = 1; // index 0 is the null node
edges_used_ = 1; // index 0 is the null edge edges_used_ = 1; // index 0 is the null edge
root_ = 1; root_ = 0;
nodes_[root_] = Node{}; 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() { u32 Tree::alloc_node() {
@@ -72,31 +119,47 @@ size_t Tree::collect_garbage(size_t node_target, size_t edge_target) {
} }
u32 Tree::prune_threshold(size_t node_target, size_t edge_target) const { 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 // A node keeps its edges through a collection with threshold T when it is
// at least T visits, and the child nodes of those edges stay. Visits only // still reachable and has at least T visits, and the child nodes of those
// shrink going down a tree, so every ancestor of such a node survives too, // edges stay. The estimate for T counts the edges and edge targets of
// and the size kept for a threshold is just the edges and child nodes of // every reachable node with at least T visits, plus the root's, which
// all nodes with at least that many visits. // 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; constexpr u32 CAP = 1 << 16;
std::vector<u64> edges_by_visits(CAP + 1, 0); 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<u8> seen(nodes_used_, 0);
std::vector<u32> stack{root_}; 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()) { while (!stack.empty()) {
const Node& node = nodes_[stack.back()]; const u32 idx = stack.back();
const Node& node = nodes_[idx];
stack.pop_back(); stack.pop_back();
if (!node.first_edge) continue; if (!node.first_edge) continue;
const u32 bucket = std::min(node.visits, CAP); const u32 bucket = std::min(node.visits, CAP);
edges_by_visits[bucket] += node.num_edges; u64 children = 0;
for (u32 i = 0; i < node.num_edges; i++) { for (u32 i = 0; i < node.num_edges; i++) {
const u32 child = edges_[node.first_edge + i].child; const u32 child = edges_[node.first_edge + i].child;
if (!child) continue; if (!child) continue;
children_by_visits[bucket]++; children++;
stack.push_back(child); 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;
} }
} }
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_nodes + children_by_visits[v] > node_target || kept_edges + edges_by_visits[v] > edge_target) if (kept_nodes + children_by_visits[v] > node_target || kept_edges + edges_by_visits[v] > edge_target)
return v + 1; return v + 1;
@@ -109,8 +172,9 @@ u32 Tree::prune_threshold(size_t node_target, size_t edge_target) const {
size_t Tree::compact(u32 new_root, u32 min_visits) { size_t Tree::compact(u32 new_root, u32 min_visits) {
// Mark: everything reachable from the new root stays. A node below the // 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 // 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 // visits and Q, as its own value u with weight base, and gets expanded
// comes back to it. `blocks` collects every edge block that stays, as // 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). // (old first index, size).
std::vector<u8> marked(nodes_used_, 0); std::vector<u8> marked(nodes_used_, 0);
std::vector<std::pair<u32, u32>> blocks; std::vector<std::pair<u32, u32>> blocks;
@@ -179,6 +243,8 @@ size_t Tree::compact(u32 new_root, u32 min_visits) {
root_ = forward[new_root]; root_ = forward[new_root];
nodes_used_ = next_node; nodes_used_ = next_node;
edges_used_ = next_edge; 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 return nodes_used_ - 1; // everything but the null node
} }
@@ -189,10 +255,27 @@ 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) { 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(); tree_.clear();
Node& node = tree_.node(tree_.root()); float value;
node.key = root.key; tree_.set_root(create_node(root, true, value));
node.check = position_check(root); }
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 { i64 Searcher::elapsed_ms() const {
@@ -311,147 +394,157 @@ size_t Searcher::reuse_tree(const Position& root) {
idx = next; idx = next;
} }
// A node that was a draw by repetition or the 50-move rule inside the old // A terminal node can still be a position to play from (insufficient
// tree can be a real position to play from now; start such a root afresh. // material is never terminal at the root); start such a root afresh.
if (pos.key != root.key || tree_.node(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, from the root as `root_pos_` with the game history `history` // Debug check of the graph from the root as `root_pos_`, with the game
// (ending with the root's key): // history `history` (ending with the root's key). Each node is checked once,
// - every node is reached exactly once (in-degree 1, the root 0), and the // with the position of the first path that reaches it (positions do not
// arenas hold nothing else; // depend on the path, apart from the clocks):
// - a node's key and check match its position, and its state is the one // - every node is reachable, and the arenas hold nothing else;
// evaluate_leaf gives that position on this path; // - a node's key and check match its position, and the table finds it there;
// the table has one entry per node 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 expanded node has one edge per legal move;
// - an edge has a child node exactly when it has visits, with as many visits // - an edge has no more draws than visits, and a child node whenever it has
// as the child (a tree), and no draws yet; // a visit that was not a draw;
// - every expanded node has at least one visit more than its edges together // - N = base + the edges' visits; a node without edges has q = u;
// (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]. // - Q and u are finite and in [-1, 1].
void Searcher::verify_tree(const std::vector<u64>& history) const { void Searcher::verify_tree(const std::vector<u64>& history) const {
const auto fail = [&](u32 idx, const Position& pos, const std::string& what) { const auto fail = [&](u32 idx, const Position& pos, const std::string& what) {
const Node& n = tree_.node(idx); const Node& n = tree_.node(idx);
std::cerr << "TREE CORRUPT at node " << idx << " (" << pos.fen() << "): " << what << " visits=" << n.visits std::cerr << "GRAPH CORRUPT at node " << idx << " (" << pos.fen() << "): " << what << " visits=" << n.visits
<< " q=" << n.q << " state=" << int(n.state) << " edges=" << int(n.num_edges) << " base=" << n.base << " q=" << n.q << " u=" << n.u << " state=" << int(n.state)
<< " first=" << n.first_edge << " nodes_used=" << tree_.nodes_used() << " edges=" << int(n.num_edges) << " first=" << n.first_edge << " nodes_used=" << tree_.nodes_used()
<< " edges_used=" << tree_.edges_used() << std::endl; << " edges_used=" << tree_.edges_used() << " table=" << tree_.table_entries() << std::endl;
std::abort(); std::abort();
}; };
std::vector<u32> in_degree(tree_.nodes_used(), 0); const u32 root = tree_.root();
std::vector<u64> keys = history; if (root == 0 || root >= tree_.nodes_used()) fail(root, root_pos_, "bad root index");
struct Frame {
u32 idx;
Position pos;
int depth;
u32 next = 0;
};
std::vector<Frame> stack;
u64 nodes = 0, edges = 0;
const auto enter = [&](u32 idx, const Position& pos, int depth) { 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); const Node& node = tree_.node(idx);
nodes++; nodes++;
if (node.key != pos.key || node.check != position_check(pos)) fail(idx, pos, "key or check mismatch"); 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) 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"); fail(idx, pos, "q or u out of range");
if (!node.visits || node.visits < node.base) fail(idx, pos, "visits below base");
// The state evaluate_leaf gives this position on this path.
MoveList legal; MoveList legal;
generate_legal(pos, 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 int expected = -1; // not terminal
if (legal.empty()) { if (legal.empty()) expected = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
expected = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW; else if (pos.insufficient_material() && idx != root && !in_history) expected = TERMINAL_DRAW;
} else if (depth > 0) { const bool ok = expected >= 0 ? node.state == expected
bool repetition = false; : node.state == UNEXPANDED || node.state == EXPANDED ||
const int n = int(keys.size()); (node.state == TERMINAL_DRAW && idx != root && in_history &&
for (int back = 4; back <= pos.halfmove && back < n; back += 2) pos.insufficient_material());
if (keys[n - 1 - back] == pos.key) repetition = true; if (!ok) fail(idx, pos, "state " + std::to_string(node.state) + " expected " + std::to_string(expected));
if (pos.halfmove >= 100 || pos.insufficient_material() || repetition) expected = TERMINAL_DRAW;
}
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.state != EXPANDED) {
if (node.first_edge || node.num_edges) fail(idx, pos, "edges on a node that is not expanded"); if (node.first_edge || node.num_edges) fail(idx, pos, "edges on a node that is not expanded");
} else { if (node.visits != node.base || node.q != node.u) fail(idx, pos, "leaf with visits != base or q != u");
if (!node.first_edge || node.first_edge + node.num_edges > tree_.edges_used() || continue;
node.num_edges != legal.size()) }
fail(idx, pos, "bad edge block, legal moves " + std::to_string(legal.size())); if (!node.first_edge || node.first_edge + node.num_edges > tree_.edges_used() ||
bool seen[256] = {}; node.num_edges != legal.size())
u64 edge_visits = 0; fail(idx, pos, "bad edge block, legal moves " + std::to_string(legal.size()));
for (u32 i = 0; i < node.num_edges; i++) { bool legal_seen[256] = {};
const Edge& e = tree_.edge(node.first_edge + i); u64 edge_visits = 0;
const auto it = std::find(legal.begin(), legal.end(), Move::from_raw(e.move)); for (u32 i = 0; i < node.num_edges; i++) {
if (it == legal.end() || seen[it - legal.begin()]) fail(idx, pos, "illegal or repeated edge move"); const Edge& e = tree_.edge(node.first_edge + i);
seen[it - legal.begin()] = true; const auto it = std::find(legal.begin(), legal.end(), Move::from_raw(e.move));
if (e.draws) fail(idx, pos, "edge with draws"); if (it == legal.end() || legal_seen[it - legal.begin()]) fail(idx, pos, "illegal or repeated edge move");
if (e.child >= tree_.nodes_used()) fail(idx, pos, "edge child out of range"); legal_seen[it - legal.begin()] = true;
if (bool(e.child) != bool(e.visits)) fail(idx, pos, "edge child without visits or the reverse"); if (e.draws > e.visits) fail(idx, pos, "edge with more draws than visits");
if (e.child && e.visits != tree_.node(e.child).visits) fail(idx, pos, "edge and child visits differ"); if (e.child >= tree_.nodes_used()) fail(idx, pos, "edge child out of range");
if (e.child && ++in_degree[e.child] != 1) fail(idx, pos, "node reached twice"); if (e.visits > e.draws && !e.child) fail(idx, pos, "edge with non-draw visits and no child");
edge_visits += e.visits; 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 < 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();
} }
edges += node.num_edges;
if (node.visits != node.base + edge_visits)
fail(idx, pos, "visits != base + edge visits " + std::to_string(edge_visits));
} }
if (nodes != tree_.nodes_used() - 1 || edges != tree_.edges_used() - 1) if (nodes != tree_.nodes_used() - 1 || edges != tree_.edges_used() - 1)
fail(tree_.root(), root_pos_, fail(root, root_pos_,
"unreachable nodes or edges: reached " + std::to_string(nodes) + " nodes, " + std::to_string(edges) + "unreachable nodes or edges: reached " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges"); " 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 != nodes || tree_.table_entries() != nodes)
fail(root, root_pos_,
"table has " + std::to_string(entries) + " entries for " + std::to_string(nodes) + " nodes");
uci_io::send("info string tree verified: " + std::to_string(nodes) + " nodes, " + std::to_string(edges) + uci_io::send("info string tree verified: " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges"); " edges, " + std::to_string(entries) + " table entries");
} }
#endif #endif
float Searcher::evaluate_leaf(u32 idx, const Position& pos, int depth) { 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 = tree_.node(idx);
node = Node{};
node.key = pos.key;
node.check = position_check(pos);
MoveList moves; // Only what the position itself decides. Repetitions and the 50-move rule
generate_legal(pos, moves); // 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 (moves.empty()) { if (!has_legal_move(pos)) {
node.state = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW; node.state = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
return node.state == TERMINAL_LOSS ? -1.0f : 0.0f; value = node.state == TERMINAL_LOSS ? -1.0f : 0.0f;
} } else if (!is_root && pos.insufficient_material()) {
// The root must always produce a move, so it is never declared drawn.
if (depth > 0 && (pos.halfmove >= 100 || pos.insufficient_material() || is_repetition(pos))) {
node.state = TERMINAL_DRAW; node.state = TERMINAL_DRAW;
return 0.0f; value = 0.0f;
} else if (float q; value_hash_.probe(pos.key, q)) {
// A position searched before (dropped by a collection, or from an
// earlier search) brings its Q along.
value = q;
} else {
value = eval::value(pos);
} }
// A position searched before (a transposition, or from an earlier search) node.visits = node.base = 1;
// brings its Q along. node.u = node.q = -value;
if (float q; value_hash_.probe(pos.key, q)) return q; tree_.insert(idx);
return eval::value(pos); return idx;
} }
bool Searcher::expand(u32 idx, const Position& pos) { bool Searcher::expand(u32 idx, const Position& pos) {
@@ -493,7 +586,7 @@ u32 Searcher::select_edge(u32 idx) const {
const Node& node = tree_.node(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. Visits are N(n), the node's own evaluation included.
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;
@@ -517,7 +610,7 @@ u32 Searcher::select_edge(u32 idx) const {
const u32 c = node.first_edge + i; const u32 c = node.first_edge + i;
const Edge& e = tree_.edge(c); const Edge& e = tree_.edge(c);
// The child's Q is from the view of the side to move here. // 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 q = e.visits ? visited_edge_q(e) : fpu;
const float score = q + explore * e.prior() / float(1 + e.visits); 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;
@@ -527,91 +620,127 @@ u32 Searcher::select_edge(u32 idx) const {
return best; 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() { 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(); edge_path_.clear();
// How the playout ended; it decides what happens to the last node.
enum Leaf { NEW_NODE, TERMINAL, NOT_EXPANDED, PATH_DRAW, DEPTH_LIMIT } leaf;
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 the side to move at the end of the playout
for (;;) { for (;;) {
const Node& node = tree_.node(idx); Node& node = tree_.node(idx);
if (node.state == TERMINAL_LOSS) { if (node.state == TERMINAL_LOSS || node.state == TERMINAL_DRAW) {
value = -1.0f; value = -node.u;
leaf = TERMINAL;
break; break;
} }
if (node.state == TERMINAL_DRAW) { // A node's first visit created and evaluated it; the second creates
value = 0.0f; // its edges (moves, priors, memory).
if (node.state == UNEXPANDED && !expand(idx, pos)) {
value = -node.q;
leaf = NOT_EXPANDED;
break; break;
} }
if (node.state == UNEXPANDED) {
// Most leaves are only ever visited once, so a first visit just
// evaluates; edges (moves, priors, memory) come on the second.
if (node.visits == 0) {
value = evaluate_leaf(idx, pos, depth);
break;
}
if (!expand(idx, pos)) {
value = eval::value(pos);
break;
}
}
const u32 e = select_edge(idx); const u32 e = select_edge(idx);
Edge& edge = tree_.edge(e); Edge& edge = tree_.edge(e);
u32 child = edge.child; pos.make_move(Move::from_raw(edge.move));
const bool created = !child; history_.push_back(pos.key);
if (created) { edge_path_.push_back(e);
// The first time this move is chosen: its node is created now and depth++;
// evaluated on this visit.
child = tree_.alloc_node(); // 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) { if (!child) {
// The node arena is full: as when expansion fails, this node child = create_node(pos, false, value);
// takes the playout and the tree is collected right after. if (!child) {
gc_pending_ = true; // The node arena is full. This playout is dropped without
value = eval::value(pos); // 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; break;
} }
edge.child = child; edge.child = child;
} }
pos.make_move(Move::from_raw(edge.move)); idx = edge.child;
if (created) { path_.push_back(idx);
Node& fresh = tree_.node(child); if (depth >= MAX_PLAYOUT_DEPTH) {
fresh = Node{}; value = -tree_.node(idx).q;
fresh.key = pos.key; leaf = DEPTH_LIMIT;
fresh.check = position_check(pos); break;
} }
history_.push_back(pos.key);
path_.push_back(child);
edge_path_.push_back(e);
idx = child;
depth++;
} }
// `value` is from the view of the side to move at the leaf. Each node stores // The last node. A new node already has its one visit (N = base = 1); a
// the view of the side that moved into it, so flip before every update. // terminal node and a node that could not be expanded count one more visit
// The same result in centipawns scores the move into each node in the // of their own value (q = u stays). A path draw has no node, and a node at
// butterfly history, for the side that played it (the side to move at the // the depth limit is left as it is: only the edge into it counts the visit.
// parent, depth i - 1). Edge visits are kept equal to the child's. if (leaf == TERMINAL || leaf == NOT_EXPANDED) {
int bonus = eval::q_to_cp(std::clamp(value, -0.998f, 0.998f)); Node& node = tree_.node(path_.back());
for (size_t i = path_.size(); i-- > 0;) {
value = -value;
bonus = -bonus;
Node& node = tree_.node(path_[i]);
node.visits++; node.visits++;
node.q += (value - node.q) / float(node.visits); node.base++;
// 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 (leaf == NEW_NODE || leaf == TERMINAL || leaf == NOT_EXPANDED) {
if (node.state != TERMINAL_DRAW) value_hash_.store(history_[root_history_size_ - 1 + i], -node.q, node.visits); const Node& node = tree_.node(path_.back());
if (i) { value_hash_.store(node.key, -node.q, node.visits);
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); // 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);
// The Q from the view of the side to move at the node.
value_hash_.store(node.key, -node.q, node.visits);
} }
iterations_++; iterations_++;
@@ -657,13 +786,22 @@ void Searcher::print_info() const {
} }
std::vector<Move> Searcher::principal_variation() const { 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<Move> pv;
std::vector<u64> keys(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_));
Position pos = root_pos_;
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_edge(idx); const u32 c = best_edge(idx);
if (!c || !tree_.edge(c).visits) break; if (!c || !tree_.edge(c).visits) break;
pv.push_back(Move::from_raw(tree_.edge(c).move)); const Edge& e = tree_.edge(c);
idx = tree_.edge(c).child; 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; return pv;
} }
@@ -711,7 +849,10 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
root_pos_ = root; root_pos_ = root;
} }
#endif #endif
const size_t reused = reuse_tree(root); 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); if (!reused) clear_tree(root);
#ifdef RIGBY_VERIFY_TREE #ifdef RIGBY_VERIFY_TREE
if (reused) verify_tree(history_); if (reused) verify_tree(history_);
@@ -741,7 +882,7 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
if (print && pretty) live_.begin(); if (print && pretty) live_.begin();
// The root needs its children before the first playout, so that even a // The root needs its edges before the first playout, so that even a
// single playout leaves a move to play. // single playout leaves a move to play.
if (tree_.node(tree_.root()).state == UNEXPANDED && !expand(tree_.root(), root)) { if (tree_.node(tree_.root()).state == UNEXPANDED && !expand(tree_.root(), root)) {
clear_tree(root); clear_tree(root);
@@ -749,7 +890,7 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
expand(tree_.root(), root); expand(tree_.root(), root);
} }
// Root move visits brought along by tree reuse, for smart pruning. The // Root edge visits brought along by tree reuse, for smart pruning. The
// root's edges keep their order through collections. // root's edges keep their order through collections.
root_start_visits_.clear(); root_start_visits_.clear();
{ {
@@ -820,12 +961,10 @@ struct NodeSnapshot {
u32 base; u32 base;
u8 state; u8 state;
u16 check; u16 check;
// (move, policy, visits, draws, has a child) per edge // (move, policy, visits, draws, child's key or 0) per edge
std::vector<std::tuple<u16, u16, u32, u32, bool>> edges; std::vector<std::tuple<u16, u16, u32, u32, u64>> edges;
}; };
using MovePath = std::vector<u16>;
} // namespace } // namespace
void Searcher::self_test() { void Searcher::self_test() {
@@ -867,48 +1006,52 @@ void Searcher::self_test() {
} }
// (b) Garbage collection and rerooting keep everything they keep exactly. // (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.
const auto snapshot = [&](u32 from) { const auto snapshot = [&](u32 from) {
std::map<MovePath, NodeSnapshot> snap; std::map<u64, NodeSnapshot> snap;
std::vector<std::pair<u32, MovePath>> stack{{from, {}}}; std::vector<u8> seen(tree_.nodes_used(), 0);
std::vector<u32> stack{from};
seen[from] = 1;
while (!stack.empty()) { while (!stack.empty()) {
auto [idx, path] = stack.back(); const u32 idx = stack.back();
stack.pop_back(); stack.pop_back();
const Node& n = tree_.node(idx); const Node& n = tree_.node(idx);
NodeSnapshot s{n.key, n.visits, n.q, n.u, n.base, n.state, n.check, {}}; 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++) { for (u32 i = 0; i < n.num_edges; i++) {
const Edge& e = tree_.edge(n.first_edge + i); const Edge& e = tree_.edge(n.first_edge + i);
s.edges.emplace_back(e.move, e.policy, e.visits, e.draws, e.child != 0); s.edges.emplace_back(e.move, e.policy, e.visits, e.draws, e.child ? tree_.node(e.child).key : 0);
if (e.child) { if (e.child && !seen[e.child]) {
MovePath next = path; seen[e.child] = 1;
next.push_back(e.move); stack.push_back(e.child);
stack.push_back({e.child, next});
} }
} }
snap.emplace(path, std::move(s)); if (!snap.emplace(n.key, std::move(s)).second) self_test_failed("two nodes with one key");
} }
return snap; return snap;
}; };
// Walks the current tree from the root and compares it with `before`. // Walks the current graph from the root and compares it with `before`.
// Returns the number of nodes; `pruned_max` / `kept_min` get the largest // 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 // visits of a node that lost its edges and the smallest of a non-root node
// that kept them. // that kept them.
const auto compare = [&](const std::map<MovePath, NodeSnapshot>& before, bool allow_pruning, u32& pruned_max, const auto compare = [&](const std::map<u64, NodeSnapshot>& before, bool allow_pruning, u32& pruned_max,
u32& kept_min) { u32& kept_min) {
size_t count = 0; size_t count = 0;
pruned_max = 0; pruned_max = 0;
kept_min = ~0u; kept_min = ~0u;
std::vector<std::pair<u32, MovePath>> stack{{tree_.root(), {}}}; std::vector<u8> seen(tree_.nodes_used(), 0);
std::vector<u32> stack{tree_.root()};
seen[tree_.root()] = 1;
while (!stack.empty()) { while (!stack.empty()) {
auto [idx, path] = stack.back(); const u32 idx = stack.back();
stack.pop_back(); stack.pop_back();
count++; count++;
const Node& n = tree_.node(idx); const Node& n = tree_.node(idx);
const auto it = before.find(path); const auto it = before.find(n.key);
if (it == before.end()) self_test_failed("a node appeared from nowhere"); if (it == before.end()) self_test_failed("a node appeared from nowhere");
const NodeSnapshot& s = it->second; const NodeSnapshot& s = it->second;
if (n.key != s.key || n.check != s.check || n.visits != s.visits || n.q != s.q) if (n.check != s.check || n.visits != s.visits || n.q != s.q)
self_test_failed("node changed (key, visits or q)"); self_test_failed("node changed (check, visits or q)");
if (!s.edges.empty() && !n.num_edges) { if (!s.edges.empty() && !n.num_edges) {
if (!allow_pruning) self_test_failed("a node lost its edges in a reroot"); 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) if (n.state != UNEXPANDED || n.first_edge || n.u != n.q || n.base != n.visits)
@@ -918,15 +1061,15 @@ void Searcher::self_test() {
} }
if (n.state != s.state || n.u != s.u || n.base != s.base || n.num_edges != s.edges.size()) 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)"); self_test_failed("node changed (state, u, base or edges)");
if (n.num_edges && !path.empty()) kept_min = std::min(kept_min, n.visits); if (n.num_edges && idx != tree_.root()) kept_min = std::min(kept_min, n.visits);
for (u32 i = 0; i < n.num_edges; i++) { for (u32 i = 0; i < n.num_edges; i++) {
const Edge& e = tree_.edge(n.first_edge + i); const Edge& e = tree_.edge(n.first_edge + i);
if (std::make_tuple(e.move, e.policy, e.visits, e.draws, e.child != 0) != s.edges[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"); self_test_failed("edge changed");
if (e.child) { if (e.child && !seen[e.child]) {
MovePath next = path; seen[e.child] = 1;
next.push_back(e.move); stack.push_back(e.child);
stack.push_back({e.child, next});
} }
} }
} }
@@ -945,7 +1088,7 @@ void Searcher::self_test() {
SearchLimits limits; SearchLimits limits;
limits.nodes = 30000; limits.nodes = 30000;
// Collections down to a half, a quarter and an eighth of the tree. // Collections down to a half, a quarter and an eighth of the graph.
new_game(); new_game();
stop_flag = false; stop_flag = false;
search(root, {root.key}, limits, false); search(root, {root.key}, limits, false);
@@ -989,7 +1132,6 @@ void Searcher::self_test() {
uci_io::send("info string verify (b) reroot " + std::string(fen) + ": " + std::to_string(count) + uci_io::send("info string verify (b) reroot " + std::string(fen) + ": " + std::to_string(count) +
" nodes ok"); " nodes ok");
} }
new_game(); new_game();
uci_io::send("info string verify passed"); uci_io::send("info string verify passed");
} }
+93 -32
View File
@@ -19,13 +19,28 @@ enum NodeState : u8 {
TERMINAL_DRAW, TERMINAL_DRAW,
}; };
// The search is a graph (Monte-Carlo graph search, docs/mcgs-plan.md): one node
// per position, shared by every move order that reaches it. Q values follow
// KataGo's "Monte-Carlo Graph Search from First Principles":
// - an edge (n, a) to child c has its own visits N(n,a), how often PUCT at n
// chose a, and draws D(n,a), how many of those playouts ended in a draw of
// their path (repetition or the 50-move rule) right after a. Such draws
// belong to the path, never to a node;
// - the edge's value for the side to move at n is (N - D) / N * c.q, so a
// path draw counts 0;
// - a node has N(n) = base + sum of its edge visits, and its Q is recomputed
// from its children on every playout through it:
// q = (base * u - sum (N - D) * c.q) / N(n). `u` is the node's own
// evaluation (base 1), or the Q it had when collection took its edges
// (base = its visits then).
// A move out of a node. A node's edges sit next to each other in the edge // 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 // arena, so the node only needs the index of the first one. The edge is linked
// created the first time search selects the edge. // to its child node the first time search selects it.
struct Edge { struct Edge {
u32 child = 0; // node index, 0 = no node yet u32 child = 0; // node index, 0 = not linked yet
u32 visits = 0; // how often search chose this move here (equals the child's visits in a tree) u32 visits = 0; // N(n,a): how often search chose this move here
u32 draws = 0; // of those, playouts that ended in a draw of the path (unused while the search is a tree) u32 draws = 0; // D(n,a): of those, playouts that ended in a draw of the path after this move
u16 move = 0; u16 move = 0;
u16 policy = 0; // prior scaled to 0..65535 u16 policy = 0; // prior scaled to 0..65535
@@ -33,27 +48,27 @@ struct Edge {
}; };
static_assert(sizeof(Edge) == 16); static_assert(sizeof(Edge) == 16);
// A position, created when search first reaches it. // A position, created (and evaluated) when search first reaches it.
struct Node { struct Node {
u64 key = 0; // Zobrist key of the position u64 key = 0; // Zobrist key of the position
u32 first_edge = 0; // 0 = not expanded u32 first_edge = 0; // 0 = not expanded
u32 visits = 0; u32 visits = 0; // N(n) = base + the edges' visits
float q = 0.0f; // running mean, from the view of the side that moved into the node float q = 0.0f; // 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 float u = 0.0f; // the same view: own evaluation, or the Q kept by collection
// node keeps) but not read yet. `check` is a second fingerprint of the u32 base = 0; // weight of u
// position (see position_check). All three are for graph search.
float u = 0.0f;
u32 base = 0;
u8 num_edges = 0; u8 num_edges = 0;
// Only facts of the position itself: checkmate, stalemate, insufficient material.
u8 state = UNEXPANDED; u8 state = UNEXPANDED;
u16 check = 0; u16 check = 0; // second fingerprint of the position (position_check)
}; };
static_assert(sizeof(Node) == 32); static_assert(sizeof(Node) == 32);
// A 16-bit fingerprint of the position that does not depend on the Zobrist keys. // A 16-bit fingerprint of the position that does not depend on the Zobrist keys.
u16 position_check(const Position& pos); u16 position_check(const Position& pos);
// Two arenas: nodes and edges. Index 0 of each is null. // Two arenas, nodes and edges (index 0 of each is null), and a table from
// position to node. A position is found by its 64-bit key plus the 16-bit
// check, about 80 bits.
class Tree { class Tree {
public: public:
// Edges per node the arenas are sized for: the edge arena gets 128 of // Edges per node the arenas are sized for: the edge arena gets 128 of
@@ -66,16 +81,24 @@ public:
// 2-3x more collections in the endgames (which fill the node arena first). // 2-3x more collections in the endgames (which fill the node arena first).
static constexpr size_t EDGES_PER_NODE = 8; static constexpr size_t EDGES_PER_NODE = 8;
// Splits `bytes` between the node arena, the edge arena and the table.
void resize_bytes(size_t bytes); void resize_bytes(size_t bytes);
// Empties the graph. The caller then creates the root and sets it.
void clear(); void clear();
// A fresh node, or 0 when the node arena is full. // A fresh node, or 0 when the node arena is full.
u32 alloc_node(); u32 alloc_node();
// The index of `count` fresh edges, or 0 when the edge arena is full. // The index of `count` fresh edges, or 0 when the edge arena is full.
u32 alloc_edges(u32 count); u32 alloc_edges(u32 count);
// Makes `new_root` the root and packs its subtree to the front of the void set_root(u32 idx) { root_ = idx; }
// arenas; everything else is dropped. Returns the number of nodes kept. // The node of the position with this key and check, 0 when there is none.
u32 find(u64 key, u16 check) const;
// Enters a node, which must not be in the table yet, by its key.
void insert(u32 idx);
// Makes `new_root` the root and packs what is reachable from it 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 an arena is full: the least visited parts of the tree // Frees memory when an arena is full: the least visited parts of the graph
// are cut back to leaves until at most `keep_fraction` of each arena is in // are cut back to leaves until at most `keep_fraction` of each arena is in
// use. Returns the number of nodes kept. // use. Returns the number of nodes kept.
size_t collect_garbage(double keep_fraction); size_t collect_garbage(double keep_fraction);
@@ -92,23 +115,42 @@ public:
size_t edges_used() const { return edges_used_; } size_t edges_used() const { return edges_used_; }
size_t node_capacity() const { return nodes_.size(); } size_t node_capacity() const { return nodes_.size(); }
size_t edge_capacity() const { return edges_.size(); } size_t edge_capacity() const { return edges_.size(); }
size_t table_entries() const { return table_entries_; }
size_t table_slots() const { return table_.size(); }
// The node a table slot points to (0 = empty) and the key half it holds.
u32 table_node(size_t slot) const { return table_[slot].node; }
u32 table_key_hi(size_t slot) const { return table_[slot].key_hi; }
// How full the fuller arena is, per mille. // How full the fuller arena is, per mille.
int fill_permille() const { int fill_permille() const {
return int(std::max(nodes_used_ * 1000 / nodes_.size(), edges_used_ * 1000 / edges_.size())); return int(std::max(nodes_used_ * 1000 / nodes_.size(), edges_used_ * 1000 / edges_.size()));
} }
private: private:
// Open addressing with linear probing. The table has at least twice as
// many slots as the node arena has nodes, so it is never more than half
// full and needs no collection of its own. Nothing is deleted from it:
// after a collection or a reroot it is rebuilt from the surviving nodes.
struct Slot {
u32 key_hi = 0; // upper half of the key
u32 node = 0; // 0 = empty
};
static_assert(sizeof(Slot) == 8);
std::vector<Node> nodes_; std::vector<Node> nodes_;
std::vector<Edge> edges_; std::vector<Edge> edges_;
std::vector<Slot> table_;
size_t table_mask_ = 0;
size_t table_entries_ = 0;
size_t nodes_used_ = 0; size_t nodes_used_ = 0;
size_t edges_used_ = 0; size_t edges_used_ = 0;
u32 root_ = 1; u32 root_ = 0;
// Keeps what is reachable from `new_root`, dropping the edges of every // 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 // node with fewer than `min_visits` visits, packs both arenas to the
// front in place. // front in place and rebuilds the table.
size_t compact(u32 new_root, u32 min_visits); size_t compact(u32 new_root, u32 min_visits);
u32 prune_threshold(size_t node_target, size_t edge_target) const; u32 prune_threshold(size_t node_target, size_t edge_target) const;
void rebuild_table();
}; };
// Butterfly history for MCTS (after Vine, aronpetkovski.com/blog/butterfly-history-mcts): // Butterfly history for MCTS (after Vine, aronpetkovski.com/blog/butterfly-history-mcts):
@@ -208,8 +250,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 graph
// (split between its arenas by Tree::EDGES_PER_NODE). // (its arenas, split by Tree::EDGES_PER_NODE, and its table).
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);
@@ -244,10 +286,14 @@ 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 // The nodes of a playout, from the root, and the edges it took
// (edge_path_[i] leads from path_[i] to path_[i + 1]). // (edge_path_[i] leaves path_[i]). A playout that ends in a draw of its
// path has one edge more than nodes before the draw.
std::vector<u32> path_; std::vector<u32> path_;
std::vector<u32> edge_path_; std::vector<u32> edge_path_;
// Guards against a key collision linking positions into a loop that
// repetition detection cannot see. Real playouts end long before this.
static constexpr int MAX_PLAYOUT_DEPTH = 512;
// 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;
@@ -276,21 +322,29 @@ private:
static constexpr double GC_KEEP_FRACTION = 0.5; static constexpr double GC_KEEP_FRACTION = 0.5;
void playout(); void playout();
// First visit of a node: settles terminal states, otherwise evaluates. // First visit of a position: a new node with one visit, entered into the
float evaluate_leaf(u32 idx, const Position& pos, int depth); // table. Settles what the position itself decides (checkmate, stalemate,
// insufficient material except at the root), otherwise evaluates.
// `value` gets the result for the side to move. Returns 0 when the node
// arena is full.
u32 create_node(const Position& pos, bool is_root, float& value);
// Second visit: creates the edges 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);
// The edge PUCT picks at node `idx`. // The edge PUCT picks at node `idx`.
u32 select_edge(u32 idx) const; u32 select_edge(u32 idx) const;
// A node's Q from its own value and its children's (see Edge).
void recompute_q(Node& node) 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 graph 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`. // True when the root node's edges are exactly the legal moves of `root`.
bool root_edges_valid(const Position& root) const;
// Empties the graph, leaving an evaluated, unexpanded root for `root`.
void clear_tree(const Position& root); void clear_tree(const Position& root);
#ifdef RIGBY_VERIFY_TREE #ifdef RIGBY_VERIFY_TREE
// Checks the tree from root_pos_; `history` ends with the root's key. // Checks the graph from root_pos_; `history` ends with the root's key.
void verify_tree(const std::vector<u64>& history) const; void verify_tree(const std::vector<u64>& history) const;
#endif #endif
@@ -301,8 +355,15 @@ private:
// The edge with the most visits at node `idx`, 0 when it has none. // The edge with the most visits at node `idx`, 0 when it has none.
u32 best_edge(u32 idx) const; u32 best_edge(u32 idx) const;
// Q of an edge from the view of the side choosing it (0 when unvisited). // Q of a visited edge from the view of the side choosing it: the child's
float edge_q(const Edge& e) const { return e.visits ? tree_.node(e.child).q : 0.0f; } // Q, with draws of the path counted as 0.
float visited_edge_q(const Edge& e) const {
if (!e.draws) return tree_.node(e.child).q;
const u32 w = e.visits - e.draws;
return w ? float(w) / float(e.visits) * tree_.node(e.child).q : 0.0f;
}
// The same, 0 when the edge is unvisited.
float edge_q(const Edge& e) const { return e.visits ? visited_edge_q(e) : 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);