#pragma once #include #include #include #include #include #include #include "position.h" #include "pretty.h" namespace rigby { enum NodeState : u8 { UNEXPANDED = 0, EXPANDED, TERMINAL_LOSS, // side to move is checkmated 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 edge is linked // to its child node the first time search selects it. struct Edge { 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 float prior() const { return float(policy) * (1.0f / 65535.0f); } }; static_assert(sizeof(Edge) == 16); // 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; // 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; // 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), 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 // every 160 bytes, the node arena 32. 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). Over the 16 bench positions at 5 s and Hash 64, // 8 gave 184 collections (main: 200), as few as 13 did, without 13's // 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); 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. Nothing is moved or dropped: what the new // root no longer reaches goes at the next collection. Returns the number // of nodes in the graph. size_t reroot(u32 new_root); // 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); // The same with explicit targets (in slots, null slots included). size_t collect_garbage(size_t node_target, size_t edge_target); 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 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(); } 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 nodes_; std::vector edges_; std::vector table_; size_t table_mask_ = 0; size_t table_entries_ = 0; size_t nodes_used_ = 0; size_t edges_used_ = 0; u32 root_ = 0; // Keeps what is reachable from `new_root`, dropping the edges of every // 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): // every playout scores each move on its path with the playout's result, and // the score is added to the move's policy logit when a node is expanded. class ButterflyHistory { public: // Value of a move's entry at which it shifts the policy logit by 1. static constexpr float LOGIT_SCALE = 16384.0f; void clear() { table_ = {}; } int get(int stm, Move m) const { return table_[stm][m.from()][m.to()]; } // `bonus` is the playout's result for the side that played `m`, in // centipawns. Entries pull towards it and saturate near +-8192. void update(int stm, Move m, int bonus) { i16& entry = table_[stm][m.from()][m.to()]; const int v = entry + bonus - entry * std::abs(bonus) / 8192; entry = i16(std::clamp(v, -32000, 32000)); } private: std::array, 64>, 2> table_{}; }; // Q of positions searched before, from the view of the side to move there // (as in Monty and Vine). Every node of a playout's path stores its Q here; // a leaf whose position is found takes that value instead of a fresh // evaluation. Transpositions are common: 37-85% of leaf evaluations in a // 5-second search repeat a position already evaluated in the same search. class ValueHash { public: void resize(size_t entries) { table_.assign(std::max(entries, 1), Entry{}); table_.shrink_to_fit(); } void clear() { std::fill(table_.begin(), table_.end(), Entry{}); } bool probe(u64 key, float& q) const { const Entry& e = table_[key % table_.size()]; if (!e.visits || e.check != u32(key >> 32)) return false; q = e.q; return true; } // A different position always replaces the entry; the same one only with // at least as many visits. void store(u64 key, float q, u32 visits) { Entry& e = table_[key % table_.size()]; if (e.check == u32(key >> 32) && visits < e.visits) return; e = Entry{u32(key >> 32), visits, q}; } static constexpr size_t ENTRY_BYTES = 12; private: struct Entry { u32 check = 0; u32 visits = 0; float q = 0.0f; }; std::vector table_; }; struct SearchLimits { u64 nodes = 0; i64 movetime = 0; i64 time[2] = {0, 0}; i64 inc[2] = {0, 0}; int movestogo = 0; int depth = 0; bool infinite = false; }; struct SearchParams { float cpuct = 1.60f; // At the root: cpuct x 1.458, Monty's root_cpuct / cpuct (0.4119 / 0.2826). float root_cpuct = 2.33f; // cpuct is multiplied by 1 + ln((N + scale) / scale) for a node with N visits // (Monty: 64 x 128). float cpuct_visit_scale = 8192.0f; float fpu_reduction = 0.30f; float policy_temperature = 1.00f; i64 move_overhead = 20; }; struct SearchResult { Move best; u64 nodes = 0; // playouts u64 tree_positions = 0; // positions visited across all playouts (bench signature) i64 time_ms = 0; }; class Searcher { public: SearchParams params; std::atomic stop_flag{false}; // Coloured output for a human at a terminal instead of UCI info lines. bool pretty = false; Searcher(); void set_hash(size_t mb) { // 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); tree_valid_ = false; } // Forget the previous tree, e.g. on ucinewgame. void new_game() { tree_valid_ = false; butterfly_.clear(); value_hash_.clear(); } // Synchronous search. `history` holds the keys of every position that led to // `root`, including the key of `root` itself (for repetition detection). SearchResult search(const Position& root, const std::vector& history, const SearchLimits& limits, bool print_info); #ifdef RIGBY_VERIFY_TREE // The `verify` command: incremental keys along random games, and garbage // collection and rerooting against a snapshot of the tree. Aborts on a failure. void self_test(); #endif private: using Clock = std::chrono::steady_clock; Tree tree_; // Kept between moves of a game, like the tree. ButterflyHistory butterfly_; Position root_pos_; ValueHash value_hash_; std::vector history_; size_t root_history_size_ = 0; // 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 path_; std::vector 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; Position prev_root_; std::vector prev_history_; Clock::time_point start_time_; i64 time_limit_ms_ = 0; // soft limit i64 hard_limit_ms_ = 0; static constexpr i64 HARD_LIMIT_FACTOR = 3; // The limit comes from the game clock (not movetime), so stopping early saves time. bool clock_search_ = false; std::vector root_start_visits_; // Lc0's default: the remaining playouts are divided by this before asking // whether another root move could still overtake the best one. static constexpr double SMART_PRUNING_FACTOR = 1.33; u64 iterations_ = 0; u64 depth_sum_ = 0; int seldepth_ = 0; bool gc_pending_ = false; int gc_runs_ = 0; size_t reused_ = 0; u64 node_limit_ = 0; pretty::LiveView live_; // Share of the arena kept after a collection. static constexpr double GC_KEEP_FRACTION = 0.5; void playout(); // 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 graph and makes it the root. // Returns the number of nodes in the graph (some may no longer be // reachable), 0 when nothing could be reused. size_t reuse_tree(const Position& 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 graph from root_pos_; `history` ends with the root's key. // `collected`: right after a collection, when every node must be reachable. void verify_tree(const std::vector& history, bool collected = false) const; #endif void compute_time_limit(const SearchLimits& limits); i64 elapsed_ms() const; bool should_stop(const SearchLimits& limits) const; bool best_move_settled(i64 ms, i64 limit_ms) const; // The edge with the most visits at node `idx`, 0 when it has none. u32 best_edge(u32 idx) const; // 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 principal_variation() const; void draw_dashboard(bool done); }; } // namespace rigby