Author SHA1 Message Date
rektdieandclaude 79fd017348 mcts: reconcile the root's draw counts after reuse (MCGS plan 3.6.7)
A reused root's edges carry draw counts collected under other game
histories, while it was an inner node. Once it is the root, the game
history is common to every path, so a root move either draws (repetition
or 50-move rule, mate excepted) on every path or on none. After reuse each
root edge becomes all draws or none: a drawn edge keeps its visits as
draws, an edge that no longer draws loses its draw visits, and so does the
root, whose Q is then recomputed. UCI prints "info string reconciled N
root edges" when N > 0.

In reuse sequences from KR v K and two pawn endgames, 1 to 8 root edges
were reconciled on most moves.

The bench is unchanged: it never reuses a graph.

Checked: zero warnings; VERIFY build: `verify` (a)-(d), the VERIFY searches of plan section 6 with forced GC at Hash 1 and 2, the reuse sequence at Hash 64, Hash 1 and from the 960 start, and the go nodes 1/2, go depth 1 smoke positions. The VERIFY build also checks that every visited root edge is all
draws exactly when its move draws, after every reuse, collection and
search.

Bench: 764208

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:36:03 +01:00
7 changed files with 146 additions and 118 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
# Rigby - MCGS chess engine # Rigby - MCTS chess engine
# OpenBench calls: make EXE=<name> [EVALFILE=<net>] [CXX=<compiler>] # OpenBench calls: make EXE=<name> [EVALFILE=<net>] [CXX=<compiler>]
# POLICYFILE=<net> picks the built-in policy network; POLICYFILE= builds none # POLICYFILE=<net> picks the built-in policy network; POLICYFILE= builds none
# (move heuristics). # (move heuristics).
+15 -22
View File
@@ -1,8 +1,8 @@
# Rigby # Rigby
Rigby is a UCI chess engine built on Monte Carlo Graph Search (MCGS) with PUCT Rigby is a UCI chess engine built on Monte Carlo Tree Search (PUCT). The goal is a
selection. The goal is a neural-network-guided MCGS engine with a value and policy neural-network-guided MCTS engine, later a Monte Carlo Graph Search (MCGS), with a
network trained with [bullet](https://github.com/jw1912/bullet) on value and policy network trained with [bullet](https://github.com/jw1912/bullet) on
data generated by Leela Chess Zero, and CUDA inference. data generated by Leela Chess Zero, and CUDA inference.
Every change is validated with SPRT on OpenBench. Every change is validated with SPRT on OpenBench.
@@ -14,14 +14,8 @@ Every change is validated with SPRT on OpenBench.
- Chess960: any castling rook placement, X-FEN and Shredder-FEN castling rights, - Chess960: any castling rook placement, X-FEN and Shredder-FEN castling rights,
`UCI_Chess960` for king-takes-rook castling notation. Verified with the 960 `UCI_Chess960` for king-takes-rook castling notation. Verified with the 960
positions of the standard Chess960 perft suite to depth 5 (`perftfile`). positions of the standard Chess960 perft suite to depth 5 (`perftfile`).
- Monte Carlo Graph Search: a position reached by different move orders is one - PUCT search: node arena with contiguous children, first-play urgency reduction,
node, found through a key table. Edges carry their own visits, so a node's Q two-fold repetition, 50-move and insufficient-material draws inside the tree.
is the visit-weighted mix of its children. PUCT selection with first-play
urgency reduction. A playout stops at a child that already has more visits
than the edge leading to it and backs up that child's Q.
- Repetition and 50-move draws depend on the path, so they are counted only on
the edges of the current path, never stored in nodes. Insufficient-material
draws are terminal nodes.
- Value: a `(768 -> 128)x2 -> 1` network trained with bullet on Lc0 data - Value: a `(768 -> 128)x2 -> 1` network trained with bullet on Lc0 data
(`networks/rigby-value-v1.bin`, embedded at build time; see `train/README.md`), (`networks/rigby-value-v1.bin`, embedded at build time; see `train/README.md`),
behind a capture-only quiescence search. behind a capture-only quiescence search.
@@ -29,11 +23,11 @@ Every change is validated with SPRT on OpenBench.
(`networks/rigby-policy-v1.bin`, embedded at build time; see `train/README.md`). (`networks/rigby-policy-v1.bin`, embedded at build time; see `train/README.md`).
Built without one (`POLICYFILE=`), move heuristics (captures, promotions, Built without one (`POLICYFILE=`), move heuristics (captures, promotions,
checks, pawn threats). checks, pawn threats).
- Graph reuse between moves: only the root moves to the new position. The next - Tree reuse between moves: the subtree of the new position is packed to the
collection keeps what the root reaches. front of the node arena in place, so it costs no extra memory.
- When the node or edge arena is full, the least visited parts of the graph are - When the arena is full, the least visited parts of the tree are cut back to
cut back to leaves (keeping their visits and Q), the rest is packed in place leaves (keeping their visits and Q) and the rest is packed, so search never
and the key table is rebuilt, so search never stops expanding. stops expanding.
- Single-threaded. - Single-threaded.
## Building ## Building
@@ -50,10 +44,9 @@ make EVALFILE=path/to/quantised.bin
`EVALFILE` defaults to `networks/rigby-value-v1.bin`. `POLICYFILE` defaults to `EVALFILE` defaults to `networks/rigby-value-v1.bin`. `POLICYFILE` defaults to
`networks/rigby-policy-v1.bin`; `POLICYFILE=` builds the move heuristics instead. `networks/rigby-policy-v1.bin`; `POLICYFILE=` builds the move heuristics instead.
Compiling with `-DRIGBY_VERIFY_TREE` checks the whole graph before and after every Compiling with `-DRIGBY_VERIFY_TREE` checks the whole tree before and after every
reuse and after every collection (legal moves, visit counts, keys and the key table) reuse and after every collection (legal moves, visit counts) and aborts on the first
and aborts on the first inconsistency. Such a build also has a `verify` command that inconsistency. It is slow, for debugging only.
runs these checks on test positions. It is slow, for debugging only.
## UCI ## UCI
@@ -91,7 +84,7 @@ terminal).
| Option | Default | Meaning | | Option | Default | Meaning |
| --- | --- | --- | | --- | --- | --- |
| Hash | 64 | Graph memory in MB: 32-byte nodes, 16-byte edges and the key table. | | Hash | 64 | Tree memory in MB. A node takes 20 bytes. |
| Threads | 1 | Only 1 for now. | | Threads | 1 | Only 1 for now. |
| MoveOverhead | 20 | Milliseconds kept back per move. | | MoveOverhead | 20 | Milliseconds kept back per move. |
| CPuct | 160 | Exploration constant x100. | | CPuct | 160 | Exploration constant x100. |
@@ -104,5 +97,5 @@ terminal).
## Bench ## Bench
`Rigby bench` runs 5000 playouts on each of 16 positions. The reported node count is `Rigby bench` runs 5000 playouts on each of 16 positions. The reported node count is
the number of positions visited in the graph over all playouts, so it changes the number of positions visited in the tree over all playouts, so it changes
whenever search behaviour changes, while the playout count stays fixed. whenever search behaviour changes, while the playout count stays fixed.
+2 -72
View File
@@ -8,13 +8,7 @@ only from results the owner provides.
| 1 | `mcgs-stats` | `bec9871` | 663779 (normal and `STATS=1` builds) | none (never merged) | measurement only; the branch stays on its own | | 1 | `mcgs-stats` | `bec9871` | 663779 (normal and `STATS=1` builds) | none (never merged) | measurement only; the branch stays on its own |
| 2 | `mcgs-step2-split` | `fb1b8a5` | 663779 (identical to main) | | | | 2 | `mcgs-step2-split` | `fb1b8a5` | 663779 (identical to main) | | |
| 3 | `mcgs-step3-core` | `14f672a` | 764208 | [5312](https://bench.rektdie.com/test/5312/) STC 8.0+0.08 `[0.00, 5.00]`, base `main` | failed: LLR −3.19, 4758 games, 106 lost on time | | 3 | `mcgs-step3-core` | `14f672a` | 764208 | [5312](https://bench.rektdie.com/test/5312/) STC 8.0+0.08 `[0.00, 5.00]`, base `main` | failed: LLR −3.19, 4758 games, 106 lost on time |
| 3b | `mcgs-step3-reroot` | `d38f0b1` | 764208 | [5313](https://bench.rektdie.com/test/5313/) STC 8.0+0.08 `[0.00, 5.00]`, base `main` | passed: LLR 3.09, 4600 games, 0 lost on time | | 3b | `mcgs-step3-reroot` | `d38f0b1` | 764208 | [5313](https://bench.rektdie.com/test/5313/) STC 8.0+0.08 `[0.00, 5.00]`, base `main` | |
| 5 | `mcgs-v-arena12` | `0a9bb40` | 764208 | [5314](https://bench.rektdie.com/test/5314/) STC `[0.00, 5.00]`, base `mcgs-step3-reroot` | stopped unfinished: Elo −0.99 ± 3.78, LLR −2.09, 12288 games |
| 5b | `mcgs-v-edgeq` | `e7f2bfb` | 769193 | [5315](https://bench.rektdie.com/test/5315/) STC `[0.00, 5.00]`, base `mcgs-step3-reroot` | stopped unfinished: Elo +1.10 ± 3.32, LLR −0.52, 16676 games |
| 5a | `mcgs-v-stop` | `59d5af5` | 609350 | [5316](https://bench.rektdie.com/test/5316/) STC `[0.00, 5.00]`, base `mcgs-step3-reroot` | passed: Elo +12.35 ± 6.40, LLR 3.31, 4898 games |
| 5 | `mcgs-v-pathrep` | `b7bfb0b` | 755448 | [5317](https://bench.rektdie.com/test/5317/) STC `[0.00, 5.00]`, base `mcgs-step3-reroot` | failed: Elo −2.06 ± 3.73, LLR −3.12, 12956 games |
| 5c | `mcgs-v-novaluehash` | `9e7c3ef` | 765326 | [5318](https://bench.rektdie.com/test/5318/) Non-Regression STC `[-5.00, 0.00]`, base `mcgs-step3-reroot` | passed: Elo +13.59 ± 7.51, LLR 3.16, 3120 games |
| 4 | `mcgs-v-reconcile` | `79fd017` | 764208 | [5319](https://bench.rektdie.com/test/5319/) STC `[0.00, 5.00]`, base `mcgs-step3-reroot` | stopped unfinished: Elo +1.61 ± 3.83, LLR 0.04, 12288 games |
## Step 1 measurements ## Step 1 measurements
@@ -693,68 +687,4 @@ At `go movetime 40` in the same replay, mean playouts per move were: main
### SPRT (owner) ### SPRT (owner)
- STC 8.0+0.08, `[0.00, 5.00]`, Threads=1, Hash=64, base `main` (bench - STC 8.0+0.08, `[0.00, 5.00]`, Threads=1, Hash=64, base `main` (bench
663779): https://bench.rektdie.com/test/5313/. Result as shown on the test 663779): https://bench.rektdie.com/test/5313/, outcome to be filled in.
page (0 games lost on time):
```
Elo | 12.24 +- 6.54 (95%)
SPRT | 8.0+0.08s Threads=1 Hash=64MB
LLR | 3.09 (-2.94, 2.94) [0.00, 5.00]
Games | N: 4600 W: 1533 L: 1371 D: 1696
```
This measures steps 2, 3 and 3b together against `main`. Merged into main
as PR #23 (`75098c8`).
## Variants on top of step 3b (one branch and one SPRT each)
Each branch is cut from `mcgs-step3-reroot` (`95e4909`) and tested against it
at STC 8.0+0.08, Threads=1, Hash=64, `UHO_Lichess_4852_v1.epd`, so a result
points at exactly one change. All passed the same gates before their test:
zero warnings, `verify` (a)–(d), the VERIFY searches of section 6 with forced
GC at Hash 1 and 2, the reuse sequence at Hash 64, Hash 1 and from the 960
start, and the smoke positions. There were no local games.
| branch | change | bench | test | result |
| --- | --- | ---: | --- | --- |
| `mcgs-v-arena12` | arenas sized for 12 edges per node instead of 8 | 764208 (unchanged, no GC in bench) | [5314](https://bench.rektdie.com/test/5314/) `[0.00, 5.00]` | stopped |
| `mcgs-v-edgeq` | 5b: each edge caches its child's Q; selection and recompute read only the edges (20-byte edge, no running sum) | 769193 | [5315](https://bench.rektdie.com/test/5315/) `[0.00, 5.00]` | stopped |
| `mcgs-v-stop` | 5a: a playout stops at a child with more visits than its edge | 609350 | [5316](https://bench.rektdie.com/test/5316/) `[0.00, 5.00]` | passed |
| `mcgs-v-pathrep` | selection scores Q = 0 for an edge whose child repeats the current path or the game | 755448 | [5317](https://bench.rektdie.com/test/5317/) `[0.00, 5.00]` | failed |
| `mcgs-v-novaluehash` | 5c: no value hash, all Hash to the graph | 765326 | [5318](https://bench.rektdie.com/test/5318/) Non-Regression `[-5.00, 0.00]` | passed |
| `mcgs-v-reconcile` | 3.6.7: after reuse each root edge is all draws or none | 764208 (unchanged, no reuse in bench) | [5319](https://bench.rektdie.com/test/5319/) `[0.00, 5.00]` | stopped |
Notes:
- **Arena split.** Collections over the 16 bench positions at 5 s and
Hash 64 (local, four builds running at once, so noisy): 8 edges per node
gave 67, 12 gave 53, 16 gave 51 and 20 gave 57. With 16, more collections
move into the endgames.
- **Edge-Q cache.** Root decisions still read the children's current Q.
The VERIFY build checks each cached Q (finite, in [-1, 1], 0 without a
child), and check (b) compares the cached Q too.
- **Stop rule.** The depth limit now ends a playout the same way the stop
rule does.
- **Reconciliation.** In reuse sequences from KR v K and two pawn endgames,
1–8 root edges were reconciled on most moves. The VERIFY build checks
after every reuse, collection and search that every visited root edge is
all draws exactly when its move draws.
Outcomes are in the table at the top. 5314, 5315 and 5319 were stopped
unfinished at the owner's request and are to be revisited later.
## Merged into main
| PR | branch | merge commit | bench on main |
| --- | --- | --- | ---: |
| #23 | `mcgs-step3-reroot` (steps 2, 3, 3b) | `75098c8` | 764208 |
| #24 | `mcgs-v-stop` (5a) | `150a876` | 609350 |
| #25 | `mcgs-v-novaluehash` (5c) | see `main` | 608763 |
The stop rule and the ValueHash removal each passed against
`mcgs-step3-reroot` alone. They were merged together at the owner's
request; no SPRT has measured the two together. Before the last merge the
combined code (`mcgs-v-novaluehash` with main merged in) passed the same
gates: zero warnings in both builds, `verify` (a)–(d), 300 tree checks in
the VERIFY searches with forced GC, the reuse sequences at Hash 64, Hash 1
and from the 960 start, and the smoke positions. Bench 608763, twice.
+74 -15
View File
@@ -1,4 +1,4 @@
#include "mcgs.h" #include "mcts.h"
#include <algorithm> #include <algorithm>
#include <bit> #include <bit>
@@ -259,6 +259,46 @@ size_t Tree::compact(u32 new_root, u32 min_visits) {
Searcher::Searcher() { set_hash(64); } Searcher::Searcher() { set_hash(64); }
bool Searcher::root_child_drawn(const Position& child, const std::vector<u64>& keys) {
const int n = int(keys.size());
for (int back = 4; back <= child.halfmove && back < n; back += 2)
if (keys[n - 1 - back] == child.key) return true;
return child.halfmove >= 100 && !(child.in_check() && !has_legal_move(child));
}
int Searcher::reconcile_root_edges(const Position& root) {
// Draw counts on the root's edges were collected under other game
// histories (the root was an inner node then). Now the history is common
// to every path: a move into a repetition (or past the 50-move rule)
// draws on every path, any other move on none. A drawn edge keeps its
// visits, all of them draws; an edge that is no longer drawn loses the
// draw visits, and so does the root.
Node& r = tree_.node(tree_.root());
if (r.state != EXPANDED) return 0;
int changed = 0;
std::vector<u64> keys = history_;
for (u32 i = 0; i < r.num_edges; i++) {
Edge& e = tree_.edge(r.first_edge + i);
if (!e.visits) continue;
Position child = root;
child.make_move(Move::from_raw(e.move));
keys.push_back(child.key);
const bool drawn = root_child_drawn(child, keys);
keys.pop_back();
if (drawn && e.draws != e.visits) {
e.draws = e.visits;
changed++;
} else if (!drawn && e.draws) {
r.visits -= e.draws;
e.visits -= e.draws;
e.draws = 0;
changed++;
}
}
if (changed) recompute_q(r);
return changed;
}
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 // 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. // takes part in its Q with weight 1, as at every other node.
@@ -486,6 +526,17 @@ void Searcher::verify_tree(const std::vector<u64>& history, bool collected) cons
if (it == legal.end() || legal_seen[it - legal.begin()]) fail(idx, pos, "illegal or repeated edge move"); if (it == legal.end() || legal_seen[it - legal.begin()]) fail(idx, pos, "illegal or repeated edge move");
legal_seen[it - legal.begin()] = true; legal_seen[it - legal.begin()] = true;
if (e.draws > e.visits) fail(idx, pos, "edge with more draws than visits"); if (e.draws > e.visits) fail(idx, pos, "edge with more draws than visits");
if (idx == root && e.visits) {
// The game history is common to every path from the root, so a
// root edge is all draws or none.
Position child = pos;
child.make_move(Move::from_raw(e.move));
std::vector<u64> keys = history;
keys.push_back(child.key);
if (e.draws != (root_child_drawn(child, keys) ? e.visits : 0))
fail(idx, pos, "root edge " + pos.uci(Move::from_raw(e.move)) + " has " +
std::to_string(e.draws) + " draws of " + std::to_string(e.visits));
}
if (e.child >= tree_.nodes_used()) fail(idx, pos, "edge child out of range"); if (e.child >= tree_.nodes_used()) fail(idx, pos, "edge child out of range");
if (e.visits > e.draws && !e.child) fail(idx, pos, "edge with non-draw visits and no child"); 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;
@@ -543,6 +594,10 @@ u32 Searcher::create_node(const Position& pos, bool is_root, float& value) {
} else if (!is_root && pos.insufficient_material()) { } else if (!is_root && pos.insufficient_material()) {
node.state = TERMINAL_DRAW; node.state = TERMINAL_DRAW;
value = 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 { } else {
value = eval::value(pos); value = eval::value(pos);
} }
@@ -646,7 +701,7 @@ void Searcher::playout() {
edge_path_.clear(); edge_path_.clear();
// How the playout ended; it decides what happens to the last node. // How the playout ended; it decides what happens to the last node.
enum Leaf { NEW_NODE, TERMINAL, NOT_EXPANDED, PATH_DRAW, STOPPED } leaf; 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;
@@ -708,29 +763,26 @@ void Searcher::playout() {
} }
idx = edge.child; idx = edge.child;
path_.push_back(idx); path_.push_back(idx);
// Stop rule (KataGo, plan variant 5a): a child that already has more if (depth >= MAX_PLAYOUT_DEPTH) {
// visits than this edge (other move orders reached it) is ahead of
// what this edge needs. The playout ends there: the edge counts the
// visit with the child's current value, and the child is left as it
// is. In a tree the two counts are equal and this never happens. The
// depth limit ends a playout the same way.
if (tree_.node(idx).visits > edge.visits || depth >= MAX_PLAYOUT_DEPTH) {
value = -tree_.node(idx).q; value = -tree_.node(idx).q;
leaf = STOPPED; leaf = DEPTH_LIMIT;
break; break;
} }
} }
// The last node. A new node already has its one visit (N = base = 1); a // The last node. A new node already has its one visit (N = base = 1); a
// terminal node and a node that could not be expanded count one more visit // terminal node and a node that could not be expanded count one more visit
// of their own value (q = u stays). A path draw has no node, and a node // of their own value (q = u stays). A path draw has no node, and a node at
// where the playout stopped is left as it is: only the edge into it counts // the depth limit is left as it is: only the edge into it counts the visit.
// the visit.
if (leaf == TERMINAL || leaf == NOT_EXPANDED) { if (leaf == TERMINAL || leaf == NOT_EXPANDED) {
Node& node = tree_.node(path_.back()); Node& node = tree_.node(path_.back());
node.visits++; node.visits++;
node.base++; node.base++;
} }
if (leaf == NEW_NODE || leaf == TERMINAL || leaf == NOT_EXPANDED) {
const Node& node = tree_.node(path_.back());
value_hash_.store(node.key, -node.q, node.visits);
}
// Up the path: each edge counts the visit (and the draw), and its parent // 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 // node recomputes its Q from its children. `value` is from the view of
@@ -748,6 +800,8 @@ void Searcher::playout() {
Node& node = tree_.node(path_[j]); Node& node = tree_.node(path_[j]);
node.visits++; node.visits++;
recompute_q(node); 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_++;
@@ -861,10 +915,13 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
// rests on the 80-bit key and check; the root is checked in full. // rests on the 80-bit key and check; the root is checked in full.
if (reused && !root_edges_valid(root)) reused = 0; if (reused && !root_edges_valid(root)) reused = 0;
if (!reused) clear_tree(root); if (!reused) clear_tree(root);
const int reconciled = reused ? reconcile_root_edges(root) : 0;
#ifdef RIGBY_VERIFY_TREE #ifdef RIGBY_VERIFY_TREE
if (reused) verify_tree(history_); if (reused) verify_tree(history_);
#endif #endif
if (print && !pretty && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes"); if (print && !pretty && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes");
if (print && !pretty && reconciled)
uci_io::send("info string reconciled " + std::to_string(reconciled) + " root edges");
iterations_ = 0; iterations_ = 0;
depth_sum_ = 0; depth_sum_ = 0;
seldepth_ = 0; seldepth_ = 0;
@@ -1142,14 +1199,16 @@ void Searcher::self_test() {
const size_t count = compare(before, false, pruned_max, kept_min); const size_t count = compare(before, false, pruned_max, kept_min);
if (count != before.size() || tree_.nodes_used() != nodes_before || tree_.edges_used() != edges_before) if (count != before.size() || tree_.nodes_used() != nodes_before || tree_.edges_used() != edges_before)
self_test_failed("reroot changed the graph"); self_test_failed("reroot changed the graph");
root_pos_ = pos;
verify_tree(history);
// The next collection (with room for everything) keeps exactly what the // The next collection (with room for everything) keeps exactly what the
// new root reaches, unchanged. // new root reaches, unchanged.
tree_.collect_garbage(tree_.node_capacity(), tree_.edge_capacity()); tree_.collect_garbage(tree_.node_capacity(), tree_.edge_capacity());
const size_t kept = compare(before, false, pruned_max, kept_min); const size_t kept = compare(before, false, pruned_max, kept_min);
if (kept != before.size() || kept != tree_.nodes_used() - 1) if (kept != before.size() || kept != tree_.nodes_used() - 1)
self_test_failed("collection after a reroot kept the wrong nodes"); self_test_failed("collection after a reroot kept the wrong nodes");
// As search does after reuse: the root's edges follow the game history.
root_pos_ = pos;
history_ = history;
reconcile_root_edges(pos);
verify_tree(history, true); verify_tree(history, true);
uci_io::send("info string verify (b) reroot " + std::string(fen) + ": " + std::to_string(nodes_before - 1) + uci_io::send("info string verify (b) reroot " + std::string(fen) + ": " + std::to_string(nodes_before - 1) +
" nodes, " + std::to_string(count) + " reachable from the new root, collected to " + " nodes, " + std::to_string(count) + " reachable from the new root, collected to " +
+52 -6
View File
@@ -153,7 +153,7 @@ private:
void rebuild_table(); void rebuild_table();
}; };
// Butterfly history (after Vine, aronpetkovski.com/blog/butterfly-history-mcts): // 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 // 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. // the score is added to the move's policy logit when a node is expanded.
class ButterflyHistory { class ButterflyHistory {
@@ -175,6 +175,42 @@ private:
std::array<std::array<std::array<i16, 64>, 64>, 2> table_{}; std::array<std::array<std::array<i16, 64>, 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<size_t>(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<Entry> table_;
};
struct SearchLimits { struct SearchLimits {
u64 nodes = 0; u64 nodes = 0;
i64 movetime = 0; i64 movetime = 0;
@@ -214,11 +250,11 @@ public:
Searcher(); Searcher();
void set_hash(size_t mb) { void set_hash(size_t mb) {
// All of it goes to the graph (its arenas, split by // A 32nd of the memory goes to the value hash, the rest to the graph
// Tree::EDGES_PER_NODE, and its table). The graph shares a position's // (its arenas, split by Tree::EDGES_PER_NODE, and its table).
// value between move orders, which a separate value hash did in the const size_t bytes = mb * 1024 * 1024;
// tree (plan variant 5c removed it). value_hash_.resize(bytes / 32 / ValueHash::ENTRY_BYTES);
tree_.resize_bytes(mb * 1024 * 1024); tree_.resize_bytes(bytes - bytes / 32);
tree_valid_ = false; tree_valid_ = false;
} }
@@ -226,6 +262,7 @@ public:
void new_game() { void new_game() {
tree_valid_ = false; tree_valid_ = false;
butterfly_.clear(); butterfly_.clear();
value_hash_.clear();
} }
// Synchronous search. `history` holds the keys of every position that led to // Synchronous search. `history` holds the keys of every position that led to
@@ -246,6 +283,7 @@ private:
// Kept between moves of a game, like the tree. // Kept between moves of a game, like the tree.
ButterflyHistory butterfly_; ButterflyHistory butterfly_;
Position root_pos_; Position root_pos_;
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 it took // The nodes of a playout, from the root, and the edges it took
@@ -304,6 +342,14 @@ private:
size_t reuse_tree(const Position& root); size_t reuse_tree(const Position& root);
// True when the root node's edges are exactly the legal moves of `root`. // True when the root node's edges are exactly the legal moves of `root`.
bool root_edges_valid(const Position& root) const; bool root_edges_valid(const Position& root) const;
// After reuse the game history is common to every path, so whether a
// root move is a draw by repetition or the 50-move rule is exact. Makes
// each root edge all draws or no draws accordingly (plan 3.6.7). Returns
// the number of edges changed.
int reconcile_root_edges(const Position& root);
// Whether `child`, reached from the root, is a draw of the game history
// `keys` (which ends with the child's key).
static bool root_child_drawn(const Position& child, const std::vector<u64>& keys);
// Empties the graph, leaving an evaluated, unexpanded root for `root`. // 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
+1 -1
View File
@@ -437,7 +437,7 @@ std::string banner(const std::string& name, const std::string& version, const st
Line title; Line title;
title.add(name, TITLE).add(" " + version, VALUE); title.add(name, TITLE).add(" " + version, VALUE);
Line right; Line right;
right.add("MCGS chess engine", LABEL); right.add("MCTS chess engine", LABEL);
box.top(title, right); box.top(title, right);
box.row(Line{}); box.row(Line{});
Line by; Line by;
+1 -1
View File
@@ -11,7 +11,7 @@
#include <vector> #include <vector>
#include "eval.h" #include "eval.h"
#include "mcgs.h" #include "mcts.h"
#include "perft.h" #include "perft.h"
#include "policy.h" #include "policy.h"
#include "position.h" #include "position.h"