16 Commits
Author SHA1 Message Date
rektdieandclaude 2f688d22d1 feat: prove mates in the graph (proven win/loss nodes, mate scores)
Until now only checkmate and stalemate were known for sure; a forced mate
was only felt through visits, and `score mate` was never printed.

A node is now proven won for its side to move when one of its children is
lost (shortest such mate), and proven lost when every move leads to a child
won for the other side (longest). The proof and its length in half-moves
live in the node's state byte, so the node stays 32 bytes. A proof is a
fact of the position, like checkmate: repetitions and the 50-move rule stay
on the edges of a path.

- Backprop: when a playout ends at a decided node (checkmate, a proof),
  its parent is checked, and so on up while each step proves a node. The
  root is not proven.
- A proven node keeps q = u = -1 / +1 and is treated as terminal by
  playouts (the root still chooses its move). Collection never cuts a
  proven node back, as its proof rests on its children.
- Selection plays the shortest proven win at once. The root's best move is
  the shortest proven win, never a proven loss unless all are (then the
  longest). At the root a proof counts only if the move does not draw by
  repetition or the 50-move rule and the mate fits in the half-moves the
  50-move rule leaves.
- UCI prints `score mate N` / `score mate -N` from the best root move.

Verified: zero warnings in both builds; the VERIFY build checks every
proof against its children (a win has a lost child at most one half-move
shorter, a loss only won children) and q = u = +-1; new `verify` check (e)
proves mate in 1, mate in 2 and two lost positions within 20000 playouts;
VERIFY searches with forced GC at Hash 1 and 2, reuse at Hash 64, Hash 1
and 960, smoke positions; reuse sequences along mating lines (KQ v K,
KR v K, two rooks, at Hash 64 and Hash 1) play to mate without a failure.
Mate on the 100th half-move is reported, and KQ v K with 4 half-moves left
reports no mate.

Bench: 613348

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:36:13 +01:00
claude 19a67fbb94 Merge pull request 'Rename MCTS to MCGS' (#26) from mcgs-rename into main
src/mcts.* is now src/mcgs.*; the banner, Makefile header and README say MCGS. No behaviour change, no SPRT.

Bench: 608763
2026-11-16 23:24:17 +01:00
rektdieandclaude 1ddb001e0b refactor: rename MCTS to MCGS (src/mcgs.h, src/mcgs.cpp)
Rigby searches a graph since PR #23, so the search files, the banner, the
Makefile header and the README now say MCGS. The README describes the
graph search, reuse, collection and Hash memory as they are now.
Internal names (Tree, RIGBY_VERIFY_TREE) are unchanged.

No behaviour change: zero warnings, bench identical to main twice.

Bench: 608763

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:23:39 +01:00
claude 59677616f7 Merge pull request 'MCGS: remove the value hash' (#25) from mcgs-v-novaluehash into main
Removes the ValueHash; all Hash goes to the graph (MCGS variant 5c). Merged together with the stop rule (#24) at the owner's request; no SPRT has measured the two together.

SPRT (Non-Regression, against mcgs-step3-reroot): https://bench.rektdie.com/test/5318/

Elo   | 13.59 +- 7.51 (95%)
SPRT  | 8.0+0.08s Threads=1 Hash=64MB
LLR   | 3.16 (-2.94, 2.94) [-5.00, 0.00]
Games | N: 3120 W: 1028 L: 906 D: 1186
Penta | [59, 283, 767, 379, 72]

Bench: 608763
2026-11-16 23:21:03 +01:00
rektdieandclaude 287bf93ef9 docs: MCGS merges into main (PRs 23-25) in mcgs-log
Bench: 608763

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:20:38 +01:00
rektdieandclaude 19aedfdce9 Merge main into mcgs-v-novaluehash
Brings in the stop rule (PR #24). The combined code passed the gates:
zero warnings, verify (a)-(d), VERIFY searches with forced GC, reuse at
Hash 64, Hash 1 and 960, smoke positions.

Bench: 608763

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:20:38 +01:00
claude 150a876b2a Merge pull request 'MCGS: stop a playout at a child that is ahead of its edge' (#24) from mcgs-v-stop into main
A playout stops at a child that has more visits than its edge and backs up the child's Q (MCGS variant 5a).

SPRT: https://bench.rektdie.com/test/5316/

Elo   | 12.35 +- 6.40 (95%)
SPRT  | 8.0+0.08s Threads=1 Hash=64MB
LLR   | 3.31 (-2.94, 2.94) [0.00, 5.00]
Games | N: 4898 W: 1609 L: 1435 D: 1854
Penta | [91, 544, 1073, 582, 159]

Bench: 609350
2026-11-16 23:19:45 +01:00
claude 75098c849b Merge pull request 'Monte-Carlo graph search (MCGS steps 2, 3 and 3b)' (#23) from mcgs-step3-reroot into main
Positions reached by different move orders now share one node. The plan is in docs/mcgs-plan.md, the gates and measurements in docs/mcgs-log.md.

SPRT: https://bench.rektdie.com/test/5313/

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
Penta | [109, 438, 1067, 554, 132]

Bench: 764208
2026-11-16 23:18:21 +01:00
rektdieandclaude 6e807b5565 docs: 5314, 5315 and 5319 stopped unfinished in mcgs-log
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:17:59 +01:00
rektdieandclaude e24145d0e5 docs: 5316 and 5318 passed, 5317 failed in mcgs-log
Also re-encodes two lines that were written as cp1252.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:15:35 +01:00
rektdieandclaude faa0b4700a docs: 5313 passed; six MCGS variant tests (5314-5319) in mcgs-log
Bench: 764208

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:44:28 +01:00
rektdieandclaude 9e7c3ef64a mcts: remove the value hash (MCGS variant 5c)
The graph shares a position's node, and with it its Q, between move
orders, which the value hash did for the tree. It still took 1/32 of Hash
and a store for every node of every playout path (about 6 % of playout
time in step 1). Its remaining use was positions the graph dropped in a
collection, or a new search without reuse.

All of Hash now goes to the graph. A simplification: Non-Regression SPRT.

The bench changes slightly (one Searcher runs all 16 bench positions, so
the value hash carried a few values between them).

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.

Bench: 765326

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:36:02 +01:00
rektdieandclaude 59d5af56f3 mcts: stop a playout at a child that is ahead of its edge (MCGS variant 5a)
With always-descend, a playout runs through existing nodes until it reaches
a new position or a draw of its path. In reversible endgames it wanders
through cycles: mean playout depth 28 against main's 6 in KR v K (bench
15), at 0.15x main's playouts/s, with 30 % of playouts ending in a
repetition.

KataGo's stop rule: when the child an edge leads to already has more
visits than the edge (other move orders reached it), the playout ends
there. The edge counts the visit and its parent recomputes from the
child's current Q; the child is left as it is. In a tree the two counts are
equal, so this only fires on transpositions. The depth limit now ends a
playout the same way.

The bench changes because playouts stop at transpositions.

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.

Bench: 609350

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:36:01 +01:00
rektdieandclaude 95e49098ec docs: 5312 result and step 3b (reroot, test 5313) in mcgs-log
Bench: 764208

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:20:26 +01:00
rektdieandclaude d38f0b133a mcts: reroot moves only the root index (no compaction between moves)
Step 3 rerooted by compacting what the new root reaches (plan 3.6.6,
mark/compact with T = 0). In a graph, a reversible endgame keeps almost the
whole graph reachable from the new root, so every move paid O(graph) before
its first playout. Replaying a 2+0.02 game that step 3 lost on time (Hash 16,
rook endgame, half-move clock about 70): the reroot averaged 3.3 ms per move,
max 14.5 ms, against 0.3 ms for main. Under load that is more than the
increment, and step 3 ran out of time in 2 of 100 games.

Now reroot only sets the root. Nodes the new root no longer reaches keep
their memory and their table entries (search may link to them again) until
the next collection, which keeps only what the root reaches. In the same
replay, the time before the first playout is 0 ms on average.

VERIFY: verify_tree requires every node to be reachable only right after a
collection; the table must always hold every node of the arena. Check (b)
now checks that a reroot changes nothing and that the next collection keeps
exactly the nodes the new root reaches, unchanged.

Checked: zero warnings, bench unchanged (bench never reuses a graph),
`verify` (a)-(d), the VERIFY searches of plan section 6 including 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.

Bench: 764208

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:19:17 +01:00
rektdieandclaude f4b79a472c docs: step 3 SPRT is test 5312 (STC vs main) in mcgs-log
Bench: 764208

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:59:36 +01:00
7 changed files with 437 additions and 127 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
# Rigby - MCTS chess engine
# Rigby - MCGS chess engine
# OpenBench calls: make EXE=<name> [EVALFILE=<net>] [CXX=<compiler>]
# POLICYFILE=<net> picks the built-in policy network; POLICYFILE= builds none
# (move heuristics).
+22 -15
View File
@@ -1,8 +1,8 @@
# Rigby
Rigby is a UCI chess engine built on Monte Carlo Tree Search (PUCT). The goal is a
neural-network-guided MCTS engine, later a Monte Carlo Graph Search (MCGS), with a
value and policy network trained with [bullet](https://github.com/jw1912/bullet) on
Rigby is a UCI chess engine built on Monte Carlo Graph Search (MCGS) with PUCT
selection. The goal is a neural-network-guided MCGS engine with a value and policy
network trained with [bullet](https://github.com/jw1912/bullet) on
data generated by Leela Chess Zero, and CUDA inference.
Every change is validated with SPRT on OpenBench.
@@ -14,8 +14,14 @@ Every change is validated with SPRT on OpenBench.
- Chess960: any castling rook placement, X-FEN and Shredder-FEN castling rights,
`UCI_Chess960` for king-takes-rook castling notation. Verified with the 960
positions of the standard Chess960 perft suite to depth 5 (`perftfile`).
- PUCT search: node arena with contiguous children, first-play urgency reduction,
two-fold repetition, 50-move and insufficient-material draws inside the tree.
- Monte Carlo Graph Search: a position reached by different move orders is one
node, found through a key table. Edges carry their own visits, so a node's Q
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
(`networks/rigby-value-v1.bin`, embedded at build time; see `train/README.md`),
behind a capture-only quiescence search.
@@ -23,11 +29,11 @@ Every change is validated with SPRT on OpenBench.
(`networks/rigby-policy-v1.bin`, embedded at build time; see `train/README.md`).
Built without one (`POLICYFILE=`), move heuristics (captures, promotions,
checks, pawn threats).
- 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.
- When the arena is full, the least visited parts of the tree are cut back to
leaves (keeping their visits and Q) and the rest is packed, so search never
stops expanding.
- Graph reuse between moves: only the root moves to the new position. The next
collection keeps what the root reaches.
- When the node or edge arena is full, the least visited parts of the graph are
cut back to leaves (keeping their visits and Q), the rest is packed in place
and the key table is rebuilt, so search never stops expanding.
- Single-threaded.
## Building
@@ -44,9 +50,10 @@ make EVALFILE=path/to/quantised.bin
`EVALFILE` defaults to `networks/rigby-value-v1.bin`. `POLICYFILE` defaults to
`networks/rigby-policy-v1.bin`; `POLICYFILE=` builds the move heuristics instead.
Compiling with `-DRIGBY_VERIFY_TREE` checks the whole tree before and after every
reuse and after every collection (legal moves, visit counts) and aborts on the first
inconsistency. It is slow, for debugging only.
Compiling with `-DRIGBY_VERIFY_TREE` checks the whole graph before and after every
reuse and after every collection (legal moves, visit counts, keys and the key table)
and aborts on the first inconsistency. Such a build also has a `verify` command that
runs these checks on test positions. It is slow, for debugging only.
## UCI
@@ -84,7 +91,7 @@ terminal).
| Option | Default | Meaning |
| --- | --- | --- |
| Hash | 64 | Tree memory in MB. A node takes 20 bytes. |
| Hash | 64 | Graph memory in MB: 32-byte nodes, 16-byte edges and the key table. |
| Threads | 1 | Only 1 for now. |
| MoveOverhead | 20 | Milliseconds kept back per move. |
| CPuct | 160 | Exploration constant x100. |
@@ -97,5 +104,5 @@ terminal).
## Bench
`Rigby bench` runs 5000 playouts on each of 16 positions. The reported node count is
the number of positions visited in the tree over all playouts, so it changes
the number of positions visited in the graph over all playouts, so it changes
whenever search behaviour changes, while the playout count stays fixed.
+141 -8
View File
@@ -7,7 +7,14 @@ 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 |
| 2 | `mcgs-step2-split` | `fb1b8a5` | 663779 (identical to main) | | |
| 3 | `mcgs-step3-core` | `14f672a` | 764208 | [5310](https://bench.rektdie.com/test/5310/) STC 8.0+0.08 `[0.00, 5.00]`; [5311](https://bench.rektdie.com/test/5311/) LTC 40.0+0.40 `[0.00, 5.00]`; base `mcgs-step2-split` | |
| 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 |
| 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
@@ -617,11 +624,137 @@ the counter build.
The plan recommends these tests, both with Threads=1 and
`UHO_Lichess_4852_v1.epd`:
- STC 8.0+0.08, `[0.00, 5.00]`, Hash=64:
https://bench.rektdie.com/test/5310/, outcome to be filled in.
- LTC 40.0+0.40, `[0.00, 5.00]`, Hash=256:
https://bench.rektdie.com/test/5311/, outcome to be filled in.
- STC 8.0+0.08, `[0.00, 5.00]`, Threads=1, Hash=64, base `main` (bench
663779): https://bench.rektdie.com/test/5312/. Result as shown on the test
page:
Both tests use base `mcgs-step2-split` (bench 663779), so they measure step 3
alone. The owner started them knowing about the failed smoke gate; the reroot
is unchanged.
```
Elo | -8.91 +- 6.44 (95%)
SPRT | 8.0+0.08s Threads=1 Hash=64MB
LLR | -3.19 (-2.94, 2.94) [0.00, 5.00]
Games | N: 4758 W: 1504 L: 1626 D: 1628
```
The workers report 106 games lost on time (18 + 88). The earlier Rigby STC
test 5308 lost none in 1618 games.
The owner chose a single STC test against `main`, so it measures steps 2 and
3 together. Tests 5310 (STC) and 5311 (LTC) against `mcgs-step2-split` were
deleted soon after they started. The owner started the test knowing about the
failed smoke gate; the reroot is unchanged.
## Step 3b: reroot moves only the root (`mcgs-step3-reroot`)
Code at `d38f0b1`, on top of `mcgs-step3-core` (`f4b79a4`). This deviates from
plan 3.6.6, on the owner's decision after the time forfeits above.
**Bench: 764208**, unchanged, because bench never reuses a graph.
What changed:
- `Tree::reroot` only sets the root index. It no longer compacts.
- Nodes the new root no longer reaches keep their memory and their table
entries until the next collection. Search may link to them again in the
meantime. The collection keeps only what the root reaches.
- `info string reused N` now counts every node in the graph, reachable or
not.
- **VERIFY:**
- `verify_tree` requires full reachability only right after a collection.
The table must always hold every node in the arena.
- Check (b) now verifies two things: a reroot changes nothing, and the next
collection keeps exactly the nodes the new root reaches, unchanged.
Gates (owner's machine, 2026-11-16):
- Zero warnings. Bench 764208.
- `verify` (a)–(d) passed. The reroot check reported, for example, 10,803
nodes in the pawn endgame, with 10,802 reachable from the new root and
10,802 kept by the collection.
- The VERIFY searches of section 6 all passed, including forced GC: Hash 1
gave 190 and 145 collections, Hash 2 gave 104 and 77.
- The reuse sequence passed at Hash 64, at Hash 1 and from the 960 start.
- The `go nodes 1/2` and `go depth 1` smoke positions passed.
- Perft was not re-run, because move generation is untouched.
- No local games: the owner asked for the SPRT directly.
Replay of the 2+0.02 game that step 3 lost on time (game 31, Hash 16), measuring the time
before the first playout (`go nodes 1` after each move, 90 moves). This is a
local measurement:
| | mean | max |
| --- | ---: | ---: |
| main | 0.2 ms | 1 ms |
| step 3 | 3.5 ms | 13 ms |
| step 3b | 0 ms | 0 ms |
At `go movetime 40` in the same replay, mean playouts per move were: main
12,083, step 3 5,047, step 3b 5,899.
### SPRT (owner)
- 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
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.
+218 -50
View File
@@ -1,4 +1,4 @@
#include "mcts.h"
#include "mcgs.h"
#include <algorithm>
#include <bit>
@@ -106,8 +106,13 @@ u32 Tree::alloc_edges(u32 count) {
}
size_t Tree::reroot(u32 new_root) {
if (new_root == root_) return nodes_used_ - 1;
return compact(new_root, 0);
// Only the root moves. Packing what stays reachable would cost O(graph) on
// every move, because in a reversible endgame almost the whole graph stays
// reachable from the new root. Nodes that are no longer reachable keep
// their memory and their table entries (search may link to them again)
// until the next collection, which keeps only what the root reaches.
root_ = new_root;
return nodes_used_ - 1;
}
size_t Tree::collect_garbage(double keep_fraction) {
@@ -185,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;
@@ -265,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;
@@ -376,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++) {
@@ -396,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);
}
@@ -406,19 +412,25 @@ size_t Searcher::reuse_tree(const Position& root) {
// history `history` (ending with the root's key). Each node is checked once,
// with the position of the first path that reaches it (positions do not
// depend on the path, apart from the clocks):
// - every node is reachable, and the arenas hold nothing else;
// - right after a collection every node is reachable, and the arenas hold
// nothing else; at other times a reroot may have left nodes the root no
// longer reaches (they wait for the next collection);
// - a node's key and check match its position, and the table finds it there;
// the table has one entry per node and nothing else;
// the table has one entry per node in the arena, reachable or not, and
// 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;
// - N = base + the edges' visits; a node without edges has q = u;
// - Q and u are finite and in [-1, 1].
void Searcher::verify_tree(const std::vector<u64>& history) const {
void Searcher::verify_tree(const std::vector<u64>& history, bool collected) const {
const auto fail = [&](u32 idx, const Position& pos, const std::string& what) {
const Node& n = tree_.node(idx);
std::cerr << "GRAPH CORRUPT at node " << idx << " (" << pos.fen() << "): " << what << " visits=" << n.visits
@@ -458,15 +470,40 @@ void Searcher::verify_tree(const std::vector<u64>& history) const {
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()));
@@ -493,10 +530,11 @@ void Searcher::verify_tree(const std::vector<u64>& history) const {
fail(idx, pos, "visits != base + edge visits " + std::to_string(edge_visits));
}
if (nodes != tree_.nodes_used() - 1 || edges != tree_.edges_used() - 1)
const u64 all_nodes = tree_.nodes_used() - 1, all_edges = tree_.edges_used() - 1;
if (collected ? nodes != all_nodes || edges != all_edges : nodes > all_nodes || edges > all_edges)
fail(root, root_pos_,
"unreachable nodes or edges: reached " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges");
" edges of " + std::to_string(all_nodes) + " and " + std::to_string(all_edges));
// The table: one entry per node, each under its node's key.
size_t entries = 0;
@@ -507,12 +545,13 @@ void Searcher::verify_tree(const std::vector<u64>& history) const {
if (n >= tree_.nodes_used() || tree_.table_key_hi(s) != u32(tree_.node(n).key >> 32))
fail(root, root_pos_, "table slot " + std::to_string(s) + " points to a wrong node");
}
if (entries != nodes || tree_.table_entries() != nodes)
if (entries != all_nodes || tree_.table_entries() != all_nodes)
fail(root, root_pos_,
"table has " + std::to_string(entries) + " entries for " + std::to_string(nodes) + " nodes");
"table has " + std::to_string(entries) + " entries for " + std::to_string(all_nodes) + " nodes");
uci_io::send("info string tree verified: " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges, " + std::to_string(entries) + " table entries");
" edges reachable, " + std::to_string(all_nodes) + " nodes in the arena, " +
std::to_string(entries) + " table entries");
}
#endif
@@ -533,10 +572,6 @@ u32 Searcher::create_node(const Position& pos, bool is_root, float& value) {
} else if (!is_root && pos.insufficient_material()) {
node.state = TERMINAL_DRAW;
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 {
value = eval::value(pos);
}
@@ -606,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);
@@ -617,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 {
@@ -640,7 +733,7 @@ void Searcher::playout() {
edge_path_.clear();
// How the playout ended; it decides what happens to the last node.
enum Leaf { NEW_NODE, TERMINAL, NOT_EXPANDED, PATH_DRAW, DEPTH_LIMIT } leaf;
enum Leaf { NEW_NODE, TERMINAL, NOT_EXPANDED, PATH_DRAW, STOPPED } leaf;
u32 idx = tree_.root();
path_.push_back(idx);
int depth = 0;
@@ -648,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;
@@ -702,32 +797,40 @@ void Searcher::playout() {
}
idx = edge.child;
path_.push_back(idx);
if (depth >= MAX_PLAYOUT_DEPTH) {
// Stop rule (KataGo, plan variant 5a): a child that already has more
// 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;
leaf = DEPTH_LIMIT;
leaf = STOPPED;
break;
}
}
// 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
// of their own value (q = u stays). A path draw has no node, and a node at
// the depth limit is left as it is: only the edge into it counts the visit.
// of their own value (q = u stays). A path draw has no node, and a node
// where the playout stopped is left as it is: only the edge into it counts
// the visit.
if (leaf == TERMINAL || leaf == NOT_EXPANDED) {
Node& node = tree_.node(path_.back());
node.visits++;
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
// node recomputes its Q from its children. `value` is from the view of
// 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;
@@ -738,9 +841,8 @@ void Searcher::playout() {
Node& node = tree_.node(path_[j]);
node.visits++;
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);
decided = decided && j && try_prove(path_[j]);
if (!is_proven(node.state)) recompute_q(node);
}
iterations_++;
@@ -759,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;
@@ -776,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();
@@ -884,7 +994,7 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& 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);
@@ -893,9 +1003,25 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& 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
@@ -910,7 +1036,8 @@ SearchResult Searcher::search(const Position& root, const std::vector<u64>& hist
gc_pending_ = false;
gc_runs_++;
#ifdef RIGBY_VERIFY_TREE
verify_tree(std::vector<u64>(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)));
verify_tree(std::vector<u64>(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)),
true);
#endif
}
if (print && (iterations_ & info_mask) == 0) {
@@ -1104,7 +1231,7 @@ void Searcher::self_test() {
const size_t count = compare(before, true, pruned_max, kept_min);
if (count != tree_.nodes_used() - 1) self_test_failed("node count differs after collection");
if (pruned_max >= kept_min) self_test_failed("pruned a node with more visits than one kept");
verify_tree({root.key});
verify_tree({root.key}, true);
uci_io::send("info string verify (b) gc " + std::string(fen) + ": " + std::to_string(before.size()) +
" -> " + std::to_string(count) + " nodes ok");
uci_io::send("info string verify (d) table after gc: " + std::to_string(tree_.table_entries()) +
@@ -1125,18 +1252,29 @@ 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);
// A reroot only moves the root: everything stays where it was.
u32 pruned_max, kept_min;
const size_t count = compare(before, false, pruned_max, kept_min);
if (count != before.size() || count != tree_.nodes_used() - 1) self_test_failed("reroot lost nodes");
if (count != before.size() || tree_.nodes_used() != nodes_before || tree_.edges_used() != edges_before)
self_test_failed("reroot changed the graph");
root_pos_ = pos;
verify_tree(history);
uci_io::send("info string verify (b) reroot " + std::string(fen) + ": " + std::to_string(count) +
" nodes ok");
uci_io::send("info string verify (d) table after reroot: " + std::to_string(tree_.table_entries()) +
" entries for " + std::to_string(count) + " nodes ok");
// The next collection (with room for everything) keeps exactly what the
// new root reaches, unchanged.
tree_.collect_garbage(tree_.node_capacity(), tree_.edge_capacity());
const size_t kept = compare(before, false, pruned_max, kept_min);
if (kept != before.size() || kept != tree_.nodes_used() - 1)
self_test_failed("collection after a reroot kept the wrong nodes");
verify_tree(history, true);
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 " +
std::to_string(kept) + " ok");
uci_io::send("info string verify (d) table after reroot and collection: " +
std::to_string(tree_.table_entries()) + " entries for " + std::to_string(kept) + " nodes ok");
}
// (c) Draws of the path never leak into nodes: search positions where
@@ -1203,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");
}
+53 -51
View File
@@ -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)
};
@@ -94,9 +113,9 @@ public:
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.
// 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
@@ -153,7 +172,7 @@ private:
void rebuild_table();
};
// Butterfly history for MCTS (after Vine, aronpetkovski.com/blog/butterfly-history-mcts):
// Butterfly history (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 {
@@ -175,42 +194,6 @@ private:
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 {
u64 nodes = 0;
i64 movetime = 0;
@@ -250,11 +233,11 @@ public:
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);
// All of it goes to the graph (its arenas, split by
// Tree::EDGES_PER_NODE, and its table). The graph shares a position's
// value between move orders, which a separate value hash did in the
// tree (plan variant 5c removed it).
tree_.resize_bytes(mb * 1024 * 1024);
tree_valid_ = false;
}
@@ -262,7 +245,6 @@ public:
void new_game() {
tree_valid_ = false;
butterfly_.clear();
value_hash_.clear();
}
// Synchronous search. `history` holds the keys of every position that led to
@@ -283,7 +265,6 @@ private:
// Kept between moves of a game, like the tree.
ButterflyHistory butterfly_;
Position root_pos_;
ValueHash value_hash_;
std::vector<u64> history_;
size_t root_history_size_ = 0;
// The nodes of a playout, from the root, and the edges it took
@@ -331,13 +312,33 @@ 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<int> 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;
// 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.
// 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;
@@ -345,7 +346,8 @@ private:
void clear_tree(const Position& root);
#ifdef RIGBY_VERIFY_TREE
// Checks the graph from root_pos_; `history` ends with the root's key.
void verify_tree(const std::vector<u64>& history) const;
// `collected`: right after a collection, when every node must be reachable.
void verify_tree(const std::vector<u64>& history, bool collected = false) const;
#endif
void compute_time_limit(const SearchLimits& limits);
+1 -1
View File
@@ -437,7 +437,7 @@ std::string banner(const std::string& name, const std::string& version, const st
Line title;
title.add(name, TITLE).add(" " + version, VALUE);
Line right;
right.add("MCTS chess engine", LABEL);
right.add("MCGS chess engine", LABEL);
box.top(title, right);
box.row(Line{});
Line by;
+1 -1
View File
@@ -11,7 +11,7 @@
#include <vector>
#include "eval.h"
#include "mcts.h"
#include "mcgs.h"
#include "perft.h"
#include "policy.h"
#include "position.h"