diff --git a/README.md b/README.md index dd17005..7849563 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,9 @@ Every change is validated with SPRT on OpenBench. - Placeholder evaluation until the network exists: a small hand-written evaluation behind a capture-only quiescence search for the value, and move heuristics (captures, promotions, checks, pawn threats) for the policy. -- Single-threaded, no tree reuse between moves. +- Tree reuse between moves: the subtree of the new position is packed to the + front of the node arena in place, so it costs no extra memory. +- Single-threaded. ## Building @@ -28,6 +30,10 @@ make make EXE=Rigby-dev ``` +Compiling with `-DRIGBY_VERIFY_TREE` checks the whole tree before and after every +reuse (legal moves, visit counts) and aborts on the first inconsistency. It is slow, +for debugging only. + ## UCI Standard commands: `uci`, `isready`, `ucinewgame`, `position`, `go` diff --git a/src/mcts.cpp b/src/mcts.cpp index 39d1a64..5fa3f50 100644 --- a/src/mcts.cpp +++ b/src/mcts.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -33,6 +34,55 @@ u32 Tree::alloc(u32 count) { return idx; } +size_t Tree::reroot(u32 new_root) { + if (new_root == root()) return used_; + + // Every child block of the subtree, as (old first index, size). + std::vector> blocks; + std::vector stack{new_root}; + while (!stack.empty()) { + const Node& node = nodes_[stack.back()]; + stack.pop_back(); + if (!node.first_child) 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); + } + + // 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. + std::sort(blocks.begin(), blocks.end()); + std::vector dest(blocks.size()); + u32 next = 2; + for (size_t i = 0; i < blocks.size(); i++) { + dest[i] = next; + next += blocks[i].second; + } + + const auto remap = [&](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 (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)); + for (u32 j = 0; j < count; j++) { + Node& node = nodes_[dest[i] + j]; + node.first_child = remap(node.first_child); + } + } + + nodes_[root()] = new_root_node; + used_ = next; + return used_ - 1; // everything but the null slot +} + // --------------------------------------------------------------------------- // Searcher // --------------------------------------------------------------------------- @@ -84,6 +134,83 @@ bool Searcher::is_repetition(const Position& pos) const { return false; } +size_t Searcher::reuse_tree(const Position& root) { + // The new game history must continue the previous one; the keys after the + // old root are the positions reached by the moves played since. + if (!tree_valid_ || history_.size() < prev_history_.size() || + !std::equal(prev_history_.begin(), prev_history_.end(), history_.begin())) + return 0; + + u32 idx = Tree::root(); + Position pos = prev_root_; + for (size_t i = prev_history_.size(); i < history_.size(); i++) { + const Node& node = tree_[idx]; + if (node.state != EXPANDED) return 0; + + u32 next = 0; + for (u32 c = 0; c < node.num_children && !next; c++) { + Position child = pos; + child.make_move(Move::from_raw(tree_[node.first_child + c].move)); + if (child.key == history_[i]) { + next = node.first_child + c; + pos = child; + } + } + if (!next) return 0; + idx = next; + } + + // 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; + + 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 { + u32 idx; + Position pos; + }; + std::vector 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; + + 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}); + } + if (!ok || node.visits < child_visits + 1) { + 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(); + } + } + uci_io::send("info string tree verified: " + std::to_string(checked) + " nodes"); +} +#endif + float Searcher::expand(u32 idx, const Position& pos, int depth) { Node& node = tree_[idx]; @@ -252,7 +379,20 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist if (history_.empty() || history_.back() != root.key) history_.push_back(root.key); root_history_size_ = history_.size(); - tree_.clear(); +#ifdef RIGBY_VERIFY_TREE + // 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(); + root_pos_ = root; + } +#endif + const size_t reused = reuse_tree(root); + if (!reused) tree_.clear(); +#ifdef RIGBY_VERIFY_TREE + if (reused) verify_tree(); +#endif + if (print && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes"); iterations_ = 0; depth_sum_ = 0; seldepth_ = 0; @@ -264,6 +404,7 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist MoveList root_moves; generate_legal(root, root_moves); if (root_moves.empty()) { + tree_valid_ = false; if (print) uci_io::send("info depth 0 score " + std::string(root.in_check() ? "mate 0" : "cp 0")); return result; } @@ -291,6 +432,10 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist result.nodes = iterations_; result.tree_positions = iterations_ + depth_sum_; result.time_ms = elapsed_ms(); + + tree_valid_ = true; + prev_root_ = root; + prev_history_.assign(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)); return result; } diff --git a/src/mcts.h b/src/mcts.h index 3620e45..ed8c4fe 100644 --- a/src/mcts.h +++ b/src/mcts.h @@ -35,6 +35,9 @@ public: 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. + size_t reroot(u32 new_root); Node& operator[](u32 idx) { return nodes_[idx]; } const Node& operator[](u32 idx) const { return nodes_[idx]; } @@ -79,7 +82,13 @@ public: Searcher(); - void set_hash(size_t mb) { tree_.resize_mb(mb); } + void set_hash(size_t mb) { + tree_.resize_mb(mb); + tree_valid_ = false; + } + + // Forget the previous tree, e.g. on ucinewgame. + void new_game() { tree_valid_ = false; } // Synchronous search. `history` holds the keys of every position that led to // `root`, including the key of `root` itself (for repetition detection). @@ -95,6 +104,11 @@ private: size_t root_history_size_ = 0; std::vector path_; + // 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; u64 iterations_ = 0; @@ -106,6 +120,12 @@ private: float expand(u32 idx, const Position& pos, int depth); u32 select_child(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); +#ifdef RIGBY_VERIFY_TREE + void verify_tree() const; +#endif void compute_time_limit(const SearchLimits& limits); i64 elapsed_ms() const; diff --git a/src/uci.cpp b/src/uci.cpp index bc5ff2e..9857209 100644 --- a/src/uci.cpp +++ b/src/uci.cpp @@ -209,6 +209,7 @@ void uci_loop() { send("readyok"); } else if (cmd == "ucinewgame") { e.stop(); + e.searcher.new_game(); e.pos.set_fen(START_FEN); e.history = {e.pos.key}; } else if (cmd == "position") {