diff --git a/src/mcgs.cpp b/src/mcgs.cpp index 68c8b24..0545a67 100644 --- a/src/mcgs.cpp +++ b/src/mcgs.cpp @@ -190,7 +190,8 @@ size_t Tree::compact(u32 new_root, u32 min_visits) { stack.pop_back(); Node& node = nodes_[idx]; if (!node.first_edge) continue; - if (idx != new_root && node.visits < min_visits) { + // A proven node keeps its edges: its proof rests on its children. + if (idx != new_root && node.visits < min_visits && !is_proven(node.state)) { node.first_edge = 0; node.num_edges = 0; node.state = UNEXPANDED; @@ -270,7 +271,7 @@ void Searcher::clear_tree(const Position& 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; + if (!node.first_edge) return node.state == UNEXPANDED; MoveList legal; generate_legal(root, legal); if (node.num_edges != legal.size()) return false; @@ -381,7 +382,7 @@ size_t Searcher::reuse_tree(const Position& root) { Position pos = prev_root_; for (size_t i = prev_history_.size(); i < history_.size(); i++) { const Node& node = tree_.node(idx); - if (node.state != EXPANDED) return 0; + if (!node.first_edge) return 0; u32 next = 0; for (u32 c = 0; c < node.num_edges && !next; c++) { @@ -401,7 +402,7 @@ size_t Searcher::reuse_tree(const Position& root) { // A terminal node can still be a position to play from (insufficient // 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).first_edge) return 0; return tree_.reroot(idx); } @@ -419,8 +420,11 @@ size_t Searcher::reuse_tree(const Position& root) { // 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; +// position of the game history), or a mate proven by search. Repetitions +// and the 50-move rule never show in a node; +// - a proven node has its edges and q = u = -1 (won) or +1 (lost); a win +// has a lost child at most one half-move shorter, a loss has only won +// children, each at least one half-move shorter; // - an expanded node has one edge per legal move; // - an edge has no more draws than visits, and a child node whenever it has // a visit that was not a draw; @@ -466,15 +470,40 @@ void Searcher::verify_tree(const std::vector& history, bool collected) cons else if (pos.insufficient_material() && idx != root && !in_history) expected = TERMINAL_DRAW; const bool ok = expected >= 0 ? node.state == expected : node.state == UNEXPANDED || node.state == EXPANDED || + is_proven(node.state) || (node.state == TERMINAL_DRAW && idx != root && in_history && pos.insufficient_material()); if (!ok) fail(idx, pos, "state " + std::to_string(node.state) + " expected " + std::to_string(expected)); + if (is_proven(node.state)) { + const float lost_for_mover = win_plies(node.state) >= 0 ? -1.0f : 1.0f; + if (node.q != lost_for_mover || node.u != lost_for_mover) fail(idx, pos, "proven node with q or u not +-1"); + if (std::max(win_plies(node.state), loss_plies(node.state)) < 1) + fail(idx, pos, "proof of less than one half-move"); + } - 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) { + if (node.state == EXPANDED || is_proven(node.state) || node.num_edges) + fail(idx, pos, "expanded or proven node without edges"); if (node.visits != node.base || node.q != node.u) fail(idx, pos, "leaf with visits != base or q != u"); continue; } + if (node.state != EXPANDED && !is_proven(node.state)) fail(idx, pos, "edges on a node that is not expanded"); + // A proof must still follow from the children it was made from: + // proofs never change, and a kept node keeps all its children. + if (is_proven(node.state)) { + bool supported = win_plies(node.state) < 0; + for (u32 i = 0; i < node.num_edges; i++) { + const Edge& e = tree_.edge(node.first_edge + i); + const u8 cs = e.child ? tree_.node(e.child).state : u8(UNEXPANDED); + if (win_plies(node.state) >= 0) { + const int lost = loss_plies(cs); + if (lost >= 0 && lost + 1 <= win_plies(node.state)) supported = true; + } else if (win_plies(cs) < 0 || win_plies(cs) + 1 > loss_plies(node.state)) { + fail(idx, pos, "proven loss with a move that is not a proven win of at most the proof's length"); + } + } + if (!supported) fail(idx, pos, "proven win without a lost child of at most the proof's length"); + } 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())); @@ -612,9 +641,20 @@ u32 Searcher::select_edge(u32 idx) const { u32 best = node.first_edge; float best_score = -1e30f; + // A move into a position lost for the opponent ends the search here: the + // shortest such mate is played (it was visited, so its child is loaded). + u32 win = 0; + int win_outcome = 0; for (u32 i = 0; i < node.num_edges; i++) { const u32 c = node.first_edge + i; const Edge& e = tree_.edge(c); + if (e.visits && e.child) { + const int outcome = edge_outcome(idx, c); + if (outcome > win_outcome) { + win_outcome = outcome; + win = c; + } + } // The child's Q is from the view of the side to move here. const float q = e.visits ? visited_edge_q(e) : fpu; const float score = q + explore * e.prior() / float(1 + e.visits); @@ -623,7 +663,54 @@ u32 Searcher::select_edge(u32 idx) const { best = c; } } - return best; + return win ? win : best; +} + +int Searcher::edge_outcome(u32 idx, u32 c) const { + const Edge& e = tree_.edge(c); + if (!e.child) return 0; + int room = MAX_PROOF_PLIES; + if (idx == tree_.root() && root_edge_room_.size() == tree_.node(idx).num_edges) + room = root_edge_room_[c - tree_.node(idx).first_edge]; + const u8 state = tree_.node(e.child).state; + const int lost = loss_plies(state); + if (lost >= 0) return lost <= room ? PROOF_SCALE - (lost + 1) : 0; + const int won = win_plies(state); + if (won >= 0) return won <= room ? (won + 1) - PROOF_SCALE : 0; + return 0; +} + +bool Searcher::try_prove(u32 idx) { + Node& node = tree_.node(idx); + if (!node.first_edge || is_proven(node.state)) return false; + // The children's proofs are facts of their positions, so this one is a + // fact of this position too; the path that led here plays no part. + int shortest_win = MAX_PROOF_PLIES + 1, longest_loss = -1; + bool all_lost = true; + for (u32 i = 0; i < node.num_edges; i++) { + const Edge& e = tree_.edge(node.first_edge + i); + if (!e.child) { + all_lost = false; + continue; + } + const u8 state = tree_.node(e.child).state; + const int lost = loss_plies(state); + if (lost >= 0) shortest_win = std::min(shortest_win, lost + 1); + const int won = win_plies(state); + if (won >= 0) longest_loss = std::max(longest_loss, won + 1); + else all_lost = false; + } + if (shortest_win <= MAX_PROOF_PLIES) { + node.state = proven_state(true, shortest_win); + node.q = node.u = -1.0f; // the side that moved in here is lost + return true; + } + if (all_lost && longest_loss <= MAX_PROOF_PLIES) { + node.state = proven_state(false, longest_loss); + node.q = node.u = 1.0f; + return true; + } + return false; } void Searcher::recompute_q(Node& node) const { @@ -654,7 +741,9 @@ void Searcher::playout() { for (;;) { Node& node = tree_.node(idx); - if (node.state == TERMINAL_LOSS || node.state == TERMINAL_DRAW) { + // A proven node is as good as terminal; only the root goes on, it + // still has to choose its move. + if (node.state == TERMINAL_LOSS || node.state == TERMINAL_DRAW || (is_proven(node.state) && depth)) { value = -node.u; leaf = TERMINAL; break; @@ -737,6 +826,11 @@ void Searcher::playout() { // 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). + // A playout that ends at a decided node (checkmate or a proof) may decide + // its parent, and so on up while each step proves a node. The root is + // not proven here: its choice depends on the game's own repetitions. + bool decided = leaf != PATH_DRAW && path_.size() == edge_path_.size() + 1 && + (loss_plies(tree_.node(path_.back()).state) >= 0 || is_proven(tree_.node(path_.back()).state)); int bonus = eval::q_to_cp(std::clamp(value, -0.998f, 0.998f)); for (size_t j = edge_path_.size(); j-- > 0;) { bonus = -bonus; @@ -747,7 +841,8 @@ void Searcher::playout() { Node& node = tree_.node(path_[j]); node.visits++; - recompute_q(node); + decided = decided && j && try_prove(path_[j]); + if (!is_proven(node.state)) recompute_q(node); } iterations_++; @@ -766,8 +861,13 @@ u32 Searcher::best_edge(u32 idx) const { } 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 ? edge_q(a) > edge_q(b) : a.policy > b.policy) + // A proven win (the shortest) beats everything and a proven loss (the + // longest) loses to everything. Then most visits wins; ties go to the + // better Q, then to the higher prior. + const int oa = edge_outcome(idx, c), ob = edge_outcome(idx, best); + if (oa != ob ? oa > ob + : a.visits != b.visits ? a.visits > b.visits + : a.visits ? edge_q(a) > edge_q(b) : a.policy > b.policy) best = c; } return best; @@ -783,7 +883,10 @@ void Searcher::print_info() const { << seldepth_; const float q = best && tree_.edge(best).visits ? edge_q(tree_.edge(best)) : -root.q; - out << " score cp " << eval::q_to_cp(q); + const int outcome = best ? edge_outcome(tree_.root(), best) : 0; + if (outcome > 0) out << " score mate " << (outcome_plies(outcome) + 1) / 2; + else if (outcome < 0) out << " score mate -" << outcome_plies(outcome) / 2; + else out << " score cp " << eval::q_to_cp(q); out << " nodes " << iterations_ << " nps " << (ms ? iterations_ * 1000 / u64(ms) : iterations_) << " time " << ms; out << " hashfull " << tree_.fill_permille(); @@ -891,7 +994,7 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist // The root needs its edges before the first playout, so that even a // single playout leaves a move to play. - if (tree_.node(tree_.root()).state == UNEXPANDED && !expand(tree_.root(), root)) { + if (!tree_.node(tree_.root()).first_edge && !expand(tree_.root(), root)) { clear_tree(root); gc_pending_ = false; expand(tree_.root(), root); @@ -900,9 +1003,25 @@ SearchResult Searcher::search(const Position& root, const std::vector& hist // Root edge visits brought along by tree reuse, for smart pruning. The // root's edges keep their order through collections. root_start_visits_.clear(); + root_edge_room_.clear(); { + // A proof the root brought along as an inner node stays (other nodes + // may rest on it), but the root itself never uses it: its move comes + // from its edges, judged with the game's own repetitions. 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); + for (u32 i = 0; i < r.num_edges; i++) { + const Edge& e = tree_.edge(r.first_edge + i); + root_start_visits_.push_back(e.visits); + // The moves that draw here, as playouts judge them on the path, + // and the room the others leave before the 50-move rule. + Position child = root; + child.make_move(Move::from_raw(e.move)); + history_.push_back(child.key); + const bool draw = + is_repetition(child) || (child.halfmove >= 100 && !(child.in_check() && !has_legal_move(child))); + root_edge_room_.push_back(draw ? -1 : std::max(0, 100 - child.halfmove)); + history_.pop_back(); + } } // UCI reports once a second; the dashboard for a human is redrawn in place @@ -1133,7 +1252,7 @@ void Searcher::self_test() { history.push_back(pos.key); idx = tree_.edge(e).child; } - if (idx == tree_.root() || tree_.node(idx).state != EXPANDED) self_test_failed("no node to reroot to"); + if (idx == tree_.root() || !tree_.node(idx).first_edge) self_test_failed("no node to reroot to"); const auto before = snapshot(idx); const size_t nodes_before = tree_.nodes_used(), edges_before = tree_.edges_used(); tree_.reroot(idx); @@ -1222,6 +1341,36 @@ void Searcher::self_test() { " edges (" + std::to_string(fifty_edges) + " at half-move 100+), node states ok"); } + // (e) Mate proofs: the root's best move must be the proven result, at + // most as long as the known mate. verify_tree at the end of each search + // checks every proof against its children. + struct MateCase { + const char* fen; + bool win; // for the side to move + int max_plies; // the known mate, in half-moves + }; + static constexpr MateCase MATE_CASES[] = { + {"6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1", true, 1}, + {"r2qkb1r/pp2nppp/3p4/2pNN1B1/2BnP3/3P4/PPP2PPP/R2bK2R w KQkq - 1 1", true, 3}, + {"k7/8/1K6/8/8/8/8/7R b - - 0 1", false, 2}, + {"7k/8/6K1/8/8/8/8/3R4 b - - 0 1", false, 2}, + }; + for (const MateCase& c : MATE_CASES) { + Position root; + if (!root.set_fen(c.fen)) self_test_failed(std::string("bad fen ") + c.fen); + SearchLimits limits; + limits.nodes = 20000; + new_game(); + stop_flag = false; + search(root, {root.key}, limits, false); // ends with verify_tree + const u32 best = best_edge(tree_.root()); + const int outcome = best ? edge_outcome(tree_.root(), best) : 0; + if ((outcome > 0) != c.win || outcome == 0 || outcome_plies(outcome) > c.max_plies) + self_test_failed(std::string("mate not proven in ") + c.fen + ", outcome " + std::to_string(outcome)); + uci_io::send("info string verify (e) " + std::string(c.fen) + ": " + (c.win ? "mates" : "mated") + " in " + + std::to_string(outcome_plies(outcome)) + " half-moves ok"); + } + new_game(); uci_io::send("info string verify passed"); } diff --git a/src/mcgs.h b/src/mcgs.h index adbaa75..f21d347 100644 --- a/src/mcgs.h +++ b/src/mcgs.h @@ -17,8 +17,25 @@ enum NodeState : u8 { EXPANDED, TERMINAL_LOSS, // side to move is checkmated TERMINAL_DRAW, + // Proven by search, for the side to move: PROVEN + 2 * plies + win, the + // game ends in mate within `plies` half-moves whatever the loser plays. + // A proven node always has its edges: collection never cuts it back. + PROVEN, }; +// Longest proof the state byte holds. +constexpr int MAX_PROOF_PLIES = (255 - PROVEN - 1) / 2; + +inline bool is_proven(u8 state) { return state >= PROVEN; } +inline u8 proven_state(bool win, int plies) { return u8(PROVEN + 2 * plies + (win ? 1 : 0)); } +// Half-moves until the side to move is mated (0: it is checkmated), -1 when the node is not lost. +inline int loss_plies(u8 state) { + if (state == TERMINAL_LOSS) return 0; + return is_proven(state) && !((state - PROVEN) & 1) ? (state - PROVEN) >> 1 : -1; +} +// Half-moves until the side to move mates, -1 when the node is not won. +inline int win_plies(u8 state) { return is_proven(state) && ((state - PROVEN) & 1) ? (state - PROVEN) >> 1 : -1; } + // 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": @@ -57,7 +74,9 @@ struct 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. + // Only facts of the position itself: checkmate, stalemate, insufficient + // material, and mates proven from the children. A proven node keeps + // q = u = -1 (won for its side to move) or +1 (lost). u8 state = UNEXPANDED; u16 check = 0; // second fingerprint of the position (position_check) }; @@ -293,8 +312,27 @@ private: // 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`. + // The edge PUCT picks at node `idx`, or the shortest proven win. u32 select_edge(u32 idx) const; + // After a child on the path was decided: marks node `idx` won when a + // child is lost for its side to move, or lost when every move leads to a + // child won for its side to move. Returns true when it marked the node. + bool try_prove(u32 idx); + // For each root edge, the half-moves its child has left before the + // 50-move rule (100 minus its half-move clock), or -1 when the move + // itself draws by repetition or the 50-move rule. A proof below a root + // edge counts only if its mate comes within that room. + std::vector root_edge_room_; + // How edge `edge` of node `idx` ends for the side choosing it, from its + // child's proof: positive for a proven win (higher for a shorter mate), + // negative for a proven loss (higher for a longer one), 0 otherwise. At + // the root, 0 for a move that draws in the game or whose mate comes too + // late for the 50-move rule. + int edge_outcome(u32 idx, u32 edge) const; + // Half-moves to mate after `outcome` (> 0: the side choosing mates, + // < 0: it gets mated). + static int outcome_plies(int outcome) { return outcome > 0 ? PROOF_SCALE - outcome : PROOF_SCALE + outcome; } + static constexpr int PROOF_SCALE = 1000; // 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;