mcts: Monte-Carlo graph search core (MCGS step 3)
Bench: 764208
One node per position, found through a key table, as in docs/mcgs-plan.md
sections 3.1-3.5 and 3.6.5:
- Key table: open addressing with linear probing over 8-byte slots
{key_hi, node}, a power of two of at least twice the node arena. A hit
needs the full 64-bit key and the node's 16-bit check (about 80 bits).
It is rebuilt from the survivors after every collection and reroot.
- create_node: a position's first visit creates and evaluates its node
(checkmate, stalemate, insufficient material except at the root, then
ValueHash, then the net) with N = base = 1, q = u. The root is created
and evaluated through it.
- Descent: after make_move, repetition and the 50-move rule (mate first)
are judged before the lookup and recorded only as the edge's draw count.
An edge is linked on first selection, to an existing node when the
table has one. MAX_PLAYOUT_DEPTH = 512 guards against key collisions.
- Backprop: each path edge counts the visit (and the draw), each path
node recomputes q = (base*u - sum (N-D)*c.q) / N, summed in double.
ValueHash is stored for every path node; butterfly history as before.
A playout whose node allocation fails is dropped and the graph collected.
- Selection, best move, smart pruning, score, PV and dashboard read edges,
with path draws counted as 0. The PV stops after a repeated position.
- The root's edges are checked against its legal moves at search start;
the graph is cleared otherwise.
- GC threshold: visited bitmap and the root counted apart, so the estimate
stays an upper bound on a DAG.
- Hash: node arena, edge arena (8 edges per node, unchanged) and the
table share the graph's budget; the table's power of two is rounded
down or up, whichever leaves more nodes.
- VERIFY: verify_tree checks the graph per plan 3.8 (keys, table, states
from the position alone, edges, N = base + edge visits, q = u on
leaves); check (b) of `verify` identifies nodes by key.
The bench changes (663779 -> 764208) because the tree becomes a graph:
transpositions share nodes, so playouts run through existing nodes and
their depths and the positions they visit change; the root gets its own
evaluation and N = 1 + the edges' visits; and repetitions and the 50-move
rule are judged on every playout instead of once per node.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5424e1a1ce
commit
6ec8769555
2 files changed
+447
-244
No files matched your search
+93
-32
@@ -19,13 +19,28 @@ enum NodeState : u8 {
|
||||
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
|
||||
// arena, so the node only needs the index of the first one. The child node is
|
||||
// created the first time search selects the edge.
|
||||
// arena, so the node only needs the index of the first one. The edge is linked
|
||||
// to its child node the first time search selects it.
|
||||
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)
|
||||
u32 child = 0; // node index, 0 = not linked yet
|
||||
u32 visits = 0; // N(n,a): how often search chose this move here
|
||||
u32 draws = 0; // D(n,a): of those, playouts that ended in a draw of the path after this move
|
||||
u16 move = 0;
|
||||
u16 policy = 0; // prior scaled to 0..65535
|
||||
|
||||
@@ -33,27 +48,27 @@ struct Edge {
|
||||
};
|
||||
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 {
|
||||
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;
|
||||
u32 visits = 0; // N(n) = base + the edges' visits
|
||||
float q = 0.0f; // from the view of the side that moved into the node
|
||||
float u = 0.0f; // the same view: own evaluation, or the Q kept by collection
|
||||
u32 base = 0; // weight of u
|
||||
u8 num_edges = 0;
|
||||
// Only facts of the position itself: checkmate, stalemate, insufficient material.
|
||||
u8 state = UNEXPANDED;
|
||||
u16 check = 0;
|
||||
u16 check = 0; // second fingerprint of the position (position_check)
|
||||
};
|
||||
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.
|
||||
// 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 {
|
||||
public:
|
||||
// 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).
|
||||
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);
|
||||
// Empties the graph. The caller then creates the root and sets it.
|
||||
void clear();
|
||||
// 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.
|
||||
void set_root(u32 idx) { root_ = idx; }
|
||||
// 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);
|
||||
// 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
|
||||
// use. Returns the number of nodes kept.
|
||||
size_t collect_garbage(double keep_fraction);
|
||||
@@ -92,23 +115,42 @@ public:
|
||||
size_t edges_used() const { return edges_used_; }
|
||||
size_t node_capacity() const { return nodes_.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.
|
||||
int fill_permille() const {
|
||||
return int(std::max(nodes_used_ * 1000 / nodes_.size(), edges_used_ * 1000 / edges_.size()));
|
||||
}
|
||||
|
||||
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<Edge> edges_;
|
||||
std::vector<Slot> table_;
|
||||
size_t table_mask_ = 0;
|
||||
size_t table_entries_ = 0;
|
||||
size_t nodes_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
|
||||
// node with fewer than `min_visits` visits, and packs both arenas to the
|
||||
// front in place.
|
||||
// node with fewer than `min_visits` visits, packs both arenas to the
|
||||
// front in place and rebuilds the table.
|
||||
size_t compact(u32 new_root, u32 min_visits);
|
||||
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):
|
||||
@@ -208,8 +250,8 @@ public:
|
||||
Searcher();
|
||||
|
||||
void set_hash(size_t mb) {
|
||||
// A 32nd of the memory goes to the value hash, the rest to the tree
|
||||
// (split between its arenas by Tree::EDGES_PER_NODE).
|
||||
// A 32nd of the memory goes to the value hash, the rest to the graph
|
||||
// (its arenas, split by Tree::EDGES_PER_NODE, and its table).
|
||||
const size_t bytes = mb * 1024 * 1024;
|
||||
value_hash_.resize(bytes / 32 / ValueHash::ENTRY_BYTES);
|
||||
tree_.resize_bytes(bytes - bytes / 32);
|
||||
@@ -244,10 +286,14 @@ 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]).
|
||||
// The nodes of a playout, from the root, and the edges it took
|
||||
// (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> 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.
|
||||
bool tree_valid_ = false;
|
||||
@@ -276,21 +322,29 @@ private:
|
||||
static constexpr double GC_KEEP_FRACTION = 0.5;
|
||||
|
||||
void playout();
|
||||
// First visit of a node: settles terminal states, otherwise evaluates.
|
||||
float evaluate_leaf(u32 idx, const Position& pos, int depth);
|
||||
// First visit of a position: a new node with one visit, entered into the
|
||||
// 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
|
||||
// arena is full (a collection is then scheduled).
|
||||
bool expand(u32 idx, const Position& pos);
|
||||
// The edge PUCT picks at node `idx`.
|
||||
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;
|
||||
// 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.
|
||||
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);
|
||||
#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;
|
||||
#endif
|
||||
|
||||
@@ -301,8 +355,15 @@ private:
|
||||
|
||||
// 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; }
|
||||
// Q of a visited edge from the view of the side choosing it: the child's
|
||||
// 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;
|
||||
std::vector<Move> principal_variation() const;
|
||||
void draw_dashboard(bool done);
|
||||
|
||||
Reference in new issue
Block a user