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
rektdieandclaude 62e5923254 docs: step 3 SPRT links (tests 5310 STC, 5311 LTC) in mcgs-log
Bench: 764208

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:45:48 +01:00
rektdieandclaude 98fae48886 docs: step 3 (MCGS core) in mcgs-log: gates, time forfeits, measurements
Bench: 764208

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:40:44 +01:00
rektdieandclaude 14f672a666 verify: checks (c) repetition leak and (d) table after GC and reroot
(c) searches five positions with forced or frequent repetitions and
50-move draws (the knight shuffle in the game history, the perpetual-check
bench position, KR v K at half-move 95, and two pawn endgames), checks every
node state from its position alone (verify_tree), and requires the draws to
show up as edge draw counts, the 50-move ones included.
(d) reports the table against the surviving nodes after every forced
collection and reroot of (b); verify_tree checks it in full.

VERIFY builds only. Bench: 764208 (unchanged)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:25:11 +01:00
rektdieandclaude 6ec8769555 mcts: Monte-Carlo graph search core (MCGS step 3)
Bench: 764208

One node per position, found through a key table, as in docs/mcgs-plan.md
sections 3.1-3.5 and 3.6.5:

- Key table: open addressing with linear probing over 8-byte slots
  {key_hi, node}, a power of two of at least twice the node arena. A hit
  needs the full 64-bit key and the node's 16-bit check (about 80 bits).
  It is rebuilt from the survivors after every collection and reroot.
- create_node: a position's first visit creates and evaluates its node
  (checkmate, stalemate, insufficient material except at the root, then
  ValueHash, then the net) with N = base = 1, q = u. The root is created
  and evaluated through it.
- Descent: after make_move, repetition and the 50-move rule (mate first)
  are judged before the lookup and recorded only as the edge's draw count.
  An edge is linked on first selection, to an existing node when the
  table has one. MAX_PLAYOUT_DEPTH = 512 guards against key collisions.
- Backprop: each path edge counts the visit (and the draw), each path
  node recomputes q = (base*u - sum (N-D)*c.q) / N, summed in double.
  ValueHash is stored for every path node; butterfly history as before.
  A playout whose node allocation fails is dropped and the graph collected.
- Selection, best move, smart pruning, score, PV and dashboard read edges,
  with path draws counted as 0. The PV stops after a repeated position.
- The root's edges are checked against its legal moves at search start;
  the graph is cleared otherwise.
- GC threshold: visited bitmap and the root counted apart, so the estimate
  stays an upper bound on a DAG.
- Hash: node arena, edge arena (8 edges per node, unchanged) and the
  table share the graph's budget; the table's power of two is rounded
  down or up, whichever leaves more nodes.
- VERIFY: verify_tree checks the graph per plan 3.8 (keys, table, states
  from the position alone, edges, N = base + edge visits, q = u on
  leaves); check (b) of `verify` identifies nodes by key.

The bench changes (663779 -> 764208) because the tree becomes a graph:
transpositions share nodes, so playouts run through existing nodes and
their depths and the positions they visit change; the root gets its own
evaluation and N = 1 + the edges' visits; and repetitions and the 50-move
rule are judged on every playout instead of once per node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:25:02 +01:00
9 changed files with 2155 additions and 1327 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>] # 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).
+22 -15
View File
@@ -1,8 +1,8 @@
# Rigby # Rigby
Rigby is a UCI chess engine built on Monte Carlo Tree Search (PUCT). The goal is a Rigby is a UCI chess engine built on Monte Carlo Graph Search (MCGS) with PUCT
neural-network-guided MCTS engine, later a Monte Carlo Graph Search (MCGS), with a selection. The goal is a neural-network-guided MCGS engine with a value and policy
value and policy network trained with [bullet](https://github.com/jw1912/bullet) on 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,8 +14,14 @@ 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`).
- PUCT search: node arena with contiguous children, first-play urgency reduction, - Monte Carlo Graph Search: a position reached by different move orders is one
two-fold repetition, 50-move and insufficient-material draws inside the tree. 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 - 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.
@@ -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`). (`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).
- Tree reuse between moves: the subtree of the new position is packed to the - Graph reuse between moves: only the root moves to the new position. The next
front of the node arena in place, so it costs no extra memory. collection keeps what the root reaches.
- When the arena is full, the least visited parts of the tree are cut back to - When the node or edge arena is full, the least visited parts of the graph are
leaves (keeping their visits and Q) and the rest is packed, so search never cut back to leaves (keeping their visits and Q), the rest is packed in place
stops expanding. and the key table is rebuilt, so search never stops expanding.
- Single-threaded. - Single-threaded.
## Building ## Building
@@ -44,9 +50,10 @@ 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 tree before and after every Compiling with `-DRIGBY_VERIFY_TREE` checks the whole graph before and after every
reuse and after every collection (legal moves, visit counts) and aborts on the first reuse and after every collection (legal moves, visit counts, keys and the key table)
inconsistency. It is slow, for debugging only. 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 ## UCI
@@ -84,7 +91,7 @@ terminal).
| Option | Default | Meaning | | 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. | | 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. |
@@ -97,5 +104,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 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. whenever search behaviour changes, while the playout count stays fixed.
+377
View File
@@ -7,6 +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 | | 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 |
| 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 ## Step 1 measurements
@@ -381,3 +389,372 @@ step 2 were run interleaved.
`UHO_Lichess_4852_v1.epd`: link and outcome to be filled in. `UHO_Lichess_4852_v1.epd`: link and outcome to be filled in.
- LTC Non-Regression `[-5.00, 0.00]`, 40.0+0.40, Threads=1, Hash=256 (NPS drop - LTC Non-Regression `[-5.00, 0.00]`, 40.0+0.40, Threads=1, Hash=256 (NPS drop
> 3 %): link and outcome to be filled in. > 3 %): link and outcome to be filled in.
## Step 3: MCGS core (`mcgs-step3-core`)
Code at `14f672a`, on top of `mcgs-step2-split` (`5424e1a`). Commits:
- `6ec8769`: the MCGS core (search, key table, sizing, graph-safe GC
threshold, graph `verify_tree`, key-based check (b));
- `14f672a`: checks (c) and (d) of the `verify` command (VERIFY builds only).
**Bench: 764208** (step 2 and main: 663779). The bench changes for three reasons:
- The tree becomes a graph: transpositions share nodes, so playouts run on
through existing nodes, and their depths and visited positions change.
- The root gets its own evaluation, and N = 1 + the edges' visits.
- Repetitions and the 50-move rule are judged on every playout instead of
once per node.
What changed (plan 3.1–3.5 and 3.6.5):
- **Key table.** Each slot is 8 bytes, `{key_hi, node}`, with linear probing.
The table is a power of two with at least 2× the node arena's slots. A hit
needs the full key and the 16-bit check. The table is rebuilt after every
collection and reroot.
- **Node creation.** `create_node` evaluates a position on its first visit
(N = base = 1, q = u). The root is created and evaluated through it.
- **Descent.** After `make_move`, repetition and the 50-move rule (mate
first) are judged before the lookup, and they are only ever counted in
`edge.draws`. An edge links to its child on first selection, to an
existing node when the table has one. `MAX_PLAYOUT_DEPTH` is 512.
- **Backprop.** For every path node: `edge.visits++` (and `draws++` for a
path draw), `node.visits++`, and q = (base·u − Σ (N−D)·c.q) / N, summed in
`double`. ValueHash is stored for every path node, with no `TERMINAL_DRAW`
test. The butterfly update is as before.
- **Edges everywhere.** Selection, root decisions, score, PV and dashboard
use edges, with draws counted as 0. The PV also stops after a repeated
position and at 64 plies.
- **Root check.** At search start, the root's edges are checked against its
legal moves. If they differ, the graph is cleared.
- **GC threshold.** It uses a visited bitmap and counts the root apart, so
the estimate stays an upper bound on a DAG.
- **Hash split.** Hash now covers the node arena, the edge arena (still 8
edges per node) and the table. The table's power of two is rounded down or
up, whichever leaves more nodes. At Hash 64 that gives 353,894 nodes and
2^20 slots (step 2: 406,323 nodes).
Deviations and choices the plan does not cover:
- **Full node arena.** If node allocation fails, the playout is dropped
without a trace: no visit is counted and no iteration is used. The graph is
then collected. The plan only says what happens when expansion fails
(value −n.q, the node's visit counted as a base visit, so q = u stays).
- **Depth limit.** At `MAX_PLAYOUT_DEPTH`, the node reached is not changed;
only the edge into it counts the visit. The recompute reads its q anyway.
- **Terminal nodes** count each visit in `base` as well, so N = base + Σ
edge visits holds for every node and VERIFY can check it everywhere.
- **Former roots.** `verify_tree` accepts a non-terminal node with
insufficient material at the root and at positions of the game history
(former roots). Insufficient material is never terminal at the root.
- **Arena split.** It stays at 8 edges per node, the step 2 value. In graph
searches the edge arena fills first: at the end of 5 s searches,
`hashfull` comes from the edge arena. Step 4 re-measures the split, as
planned.
### Gates (owner's machine, 2026-11-16)
- **Build:** normal and VERIFY builds, zero warnings.
- **Bench:** `764208`.
- **Perft:**
- `perftsuite`: all passed (590,175,385 nodes);
- `perftfile tests/fischer.epd 5`: 960 positions, 0 failed,
17,614,927,759 nodes, 55 s.
- **VERIFY searches** (`go nodes 200000`), each ending with `tree verified`
and no abort:
- startpos;
- the transposition line;
- the history repetition (`g1f3 g8f6 f3g1 f6g8 g1f3 g8f6`);
- bench positions 11, 12, 15 and 16;
- `8/8/8/4k3/8/8/2KR4/8 w - - 95 100` (seldepth 5);
- the mate-in-1 FEN (still `g1f1`, as on main and step 2);
- the 960 start with `UCI_Chess960 true`.
- **Forced GC** (`go nodes 300000`), every collection verified:
- Hash 1: 190 collections (startpos) and 145 (960);
- Hash 2: 104 and 77.
- **Reuse sequence** (VERIFY build, `go nodes 50000`, best move plus the
second PV move, 10 moves), clean every time:
- Hash 64 (21k–69k positions reused per move);
- Hash 1 (24–42 collections per move);
- the 960 start at Hash 64.
- **`verify`**, all passed:
- (a) 96,434 plies, incremental key = FEN key.
- (b) Three forced collections (to 1/2, 1/4 and 1/8) and a reroot on 4
positions: every survivor is identical by key, including edges and child
keys, and no pruned node has more visits than a kept one.
- (c) Five positions with forced or frequent repetitions and 50-move draws
(knight shuffle in the history, perpetual check, KR v K at half-move 95,
two pawn endgames). Every node state matches its position alone, and the
draws appear on edges: 30 to 29,077 draw visits per position. In the
KR v K position, 10,504 draw edges are at half-move 100+.
- (d) After every forced collection and reroot, the table has exactly one
entry per surviving node, and the table finds each node by its position.
- **Smoke:**
- `go nodes 1`, `go nodes 2` and `go depth 1` on the section 6 positions,
two no-move positions and a KB v K root: clean.
- 20 VERIFY self-play games at `nodes=20000`, Hash 16: all ended by mate,
repetition, the 50-move rule or insufficient material, with no abort.
- **Smoke, step 3 vs main: FAILED.** 100 games at 2+0.02, Hash 16, UHO book,
cutechess-ob, concurrency 10, while the VERIFY self-play (concurrency 10)
and the owner's own game were running. Step 3 lost **2 games on time**
(games 31 and 81, both as White, rook endgames at ply 180–181, half-move
clock about 70). There were no illegal moves, disconnects or aborts. See
the next section.
- **Control:** step 3 vs main and step 2 vs main, run at the same time, 100
games each at concurrency 6. There were no time forfeits, but step 3 still
had 23 moves in 11 games that stopped at ≤ 64 playouts. Step 2 and main had
none.
### Time forfeits: rerooting a graph is O(graph)
Step 3 ended moves at 64 playouts in late endgames (the clock is checked every
64 playouts, and those moves were already past the hard limit). In both
forfeits, every step 3 move over the last 10–20 moves had 64 playouts in
about 28 ms. In the same games, main searched about 10,000 playouts per move.
Cause, measured by replaying game 31 in one session (Hash 16, local
instrumented build that is not committed):
- **Cost before the first playout.** With `go nodes 1` after each move,
step 3 averages 3.5 ms (max 14 ms), against 0.3 ms for main and step 2.
- **The reroot itself.** Over 179 reroots it took 3.3 ms on average and kept
27,262 nodes on average: mark 1.4 ms, slide and remap 1.6 ms, table rebuild
0.26 ms. The worst case was 14.5 ms with 65,081 nodes kept.
- **Why it keeps so much.** In a reversible endgame, almost the whole graph
stays reachable from the new root, because the old positions can be reached
again. A tree reroot keeps one subtree, so main's cost stays small.
- **Why the clock drains.** At 2+0.02 under heavy load, a fixed cost per move
above the 20 ms increment drains the clock.
This is a gap in plan 3.6.6. "Reroot = mark/compact with T = 0" is O(nodes
kept), and on a graph that is close to O(graph) in endgames. As instructed, I
did not change the design. Options for the owner:
- (a) Reroot by moving the root index only (unreachable parts go at the next
collection, and the table stays valid). This changes 3.6.6.
- (b) Make compaction cheaper (a forwarding array instead of `lower_bound`,
reused buffers). This is a constant factor only.
- (c) Count the setup cost in time management.
The 8+0.08 STC has a 4× larger increment, but OpenBench workers also run
under load.
### Measurements (local, owner playing a game at the same time: noisy)
**Playouts/s at 5 s per bench position, Hash 64.** One round, the four
engines interleaved per position. Step 3 is run twice: the normal build and
the counter build.
| pos | main | step 2 | step 3 | step 3 / main |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 200,122 | 181,012 | 117,808 | 0.59 |
| 2 | 148,819 | 134,104 | 111,678 | 0.75 |
| 3 | 217,946 | 202,846 | 108,144 | 0.50 |
| 4 | 220,530 | 197,230 | 106,011 | 0.48 |
| 5 | 197,654 | 171,347 | 124,401 | 0.63 |
| 6 | 168,134 | 161,465 | 113,824 | 0.68 |
| 7 | 179,816 | 162,171 | 119,518 | 0.66 |
| 8 | 173,057 | 164,973 | 127,588 | 0.74 |
| 9 | 227,084 | 204,864 | 148,048 | 0.65 |
| 10 | 335,241 | 318,534 | 192,549 | 0.57 |
| 11 | 959,036 | 912,732 | 425,445 | 0.44 |
| 12 | 774,695 | 703,203 | 361,420 | 0.47 |
| 13 | 191,421 | 175,871 | 133,590 | 0.70 |
| 14 | 199,466 | 194,403 | 147,058 | 0.74 |
| 15 | 667,244 | 678,618 | 101,590 | 0.15 |
| 16 | 4,619,553 | 4,342,926 | 3,595,617 | 0.78 |
| all | **592,489** | **556,526** | **377,088** | **0.64** (0.68 vs step 2) |
- `bench` nps, 5 alternating runs each (mean): main 2,996,116, step 2
2,974,460, step 3 2,572,979 (0.86× main).
- Playouts are longer, so playouts/s understates the positions searched.
The mean playout depth at 5 s is:
| position | main | step 2 | step 3 |
| --- | ---: | ---: | ---: |
| startpos | 14 | 14 | 13 |
| bench 11 | 12 | 12 | 16 (seldepth 80) |
| bench 15, KR v K | 6 | 6 | 28 (seldepth 100) |
With always-descend, a playout runs through existing nodes until it reaches
a new position, a repetition or the 50-move rule. In reversible endgames it
wanders through cycles. In bench 15, 30 % of playouts end in a repetition,
and the root score is 739 cp against main's 1,701. The plan leaves stopping
early to variant 5a.
- In the 2+0.02 games (heavy load), the median playouts per move was 4,480
for step 3 against 8,256 for main. In the control match it was 5,312
against 9,664, with step 2 at 9,024.
**Rates** from the counter build (5 s, Hash 64, same run as above):
| pos | playouts | mean depth | lookups | **hit %** | **path draw %** | of which 50-move % | new node % | GC |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 621,248 | 13.4 | 769,706 | 19.3 | 0.0 | 0 | 100.0 | 10 |
| 2 | 540,608 | 21.2 | 581,323 | 7.1 | 0.1 | 0 | 99.9 | 6 |
| 3 | 563,520 | 12.8 | 710,180 | 20.8 | 0.1 | 0 | 99.9 | 10 |
| 4 | 528,640 | 19.0 | 613,787 | 14.0 | 0.1 | 0 | 99.9 | 7 |
| 5 | 620,096 | 11.3 | 727,622 | 14.9 | 0.1 | 0 | 99.9 | 9 |
| 6 | 589,696 | 18.5 | 629,636 | 6.8 | 0.3 | 0 | 99.5 | 7 |
| 7 | 587,392 | 17.9 | 632,662 | 7.4 | 0.2 | 0 | 99.7 | 7 |
| 8 | 627,456 | 15.4 | 669,276 | 7.0 | 0.7 | 0 | 99.2 | 8 |
| 9 | 747,520 | 20.0 | 879,332 | 19.1 | 4.8 | 0 | 95.1 | 3 |
| 10 | 958,144 | 15.2 | 901,621 | 21.4 | 25.9 | 0 | 73.9 | 3 |
| 11 | 2,148,608 | 16.7 | 1,051,775 | 45.3 | 71.8 | 0 | 26.8 | 2 |
| 12 | 1,762,496 | 19.7 | 835,300 | 52.2 | 71.5 | 0 | 22.7 | 1 |
| 13 | 671,360 | 22.4 | 731,789 | 9.2 | 0.6 | 0 | 99.0 | 5 |
| 14 | 766,144 | 12.5 | 842,901 | 10.7 | 1.7 | 0 | 98.3 | 9 |
| 15 | 522,688 | 28.3 | 2,026,421 | 83.8 | 32.3 | 2.15 | 62.9 | 1 |
| 16 | 17,866,176 | 4.0 | 53,747 | 18.2 | 98.3 | 0 | 0.2 | 0 |
| all | 30,121,792 | 9.5 | 12,657,078 | **30.1** | **69.2** | 0.04 | 29.4 | 88 |
- **Lookup.** A lookup is the table probe when an edge is first selected (no
child linked yet). A hit links the edge to an existing node.
- **Hit rate.** 30.1 % of lookups hit over all positions: 7–21 % in
middlegames, 45–52 % in the pawn endgames and 84 % in KR v K.
- **Path draws.** 69.2 % of playouts end in a path draw, almost all by
repetition. Without position 16 (perpetual check), the figure is 26.8 %.
- **Other endings.** Over all positions, 420,673 playouts ended at a terminal
node and 87 at a node that could not be expanded. One playout was dropped
because the node arena was full, and none reached the depth limit.
- **Edge arena.** Middlegames fill the edge arena first. At 8 edges per node,
`hashfull` reached 965 at 5 s from startpos, against 661 for main.
### SPRT (owner)
The plan recommends these tests, both with Threads=1 and
`UHO_Lichess_4852_v1.epd`:
- 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:
```
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.
+1379
View File
File diff suppressed because it is too large. Load diff
+374
View File
@@ -0,0 +1,374 @@
#pragma once
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <vector>
#include "position.h"
#include "pretty.h"
namespace rigby {
enum NodeState : u8 {
UNEXPANDED = 0,
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":
// - an edge (n, a) to child c has its own visits N(n,a), how often PUCT at n
// chose a, and draws D(n,a), how many of those playouts ended in a draw of
// their path (repetition or the 50-move rule) right after a. Such draws
// belong to the path, never to a node;
// - the edge's value for the side to move at n is (N - D) / N * c.q, so a
// path draw counts 0;
// - a node has N(n) = base + sum of its edge visits, and its Q is recomputed
// from its children on every playout through it:
// q = (base * u - sum (N - D) * c.q) / N(n). `u` is the node's own
// evaluation (base 1), or the Q it had when collection took its edges
// (base = its visits then).
// A move out of a node. A node's edges sit next to each other in the edge
// arena, so the node only needs the index of the first one. The edge is linked
// to its child node the first time search selects it.
struct Edge {
u32 child = 0; // node index, 0 = not linked yet
u32 visits = 0; // N(n,a): how often search chose this move here
u32 draws = 0; // D(n,a): of those, playouts that ended in a draw of the path after this move
u16 move = 0;
u16 policy = 0; // prior scaled to 0..65535
float prior() const { return float(policy) * (1.0f / 65535.0f); }
};
static_assert(sizeof(Edge) == 16);
// A position, created (and evaluated) when search first reaches it.
struct Node {
u64 key = 0; // Zobrist key of the position
u32 first_edge = 0; // 0 = not expanded
u32 visits = 0; // N(n) = base + the edges' visits
float q = 0.0f; // from the view of the side that moved into the node
float u = 0.0f; // the same view: own evaluation, or the Q kept by collection
u32 base = 0; // weight of u
u8 num_edges = 0;
// Only facts of the position itself: checkmate, stalemate, insufficient
// material, 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)
};
static_assert(sizeof(Node) == 32);
// A 16-bit fingerprint of the position that does not depend on the Zobrist keys.
u16 position_check(const Position& pos);
// Two arenas, nodes and edges (index 0 of each is null), and a table from
// position to node. A position is found by its 64-bit key plus the 16-bit
// check, about 80 bits.
class Tree {
public:
// Edges per node the arenas are sized for: the edge arena gets 128 of
// every 160 bytes, the node arena 32. Measured in step 1 of the MCGS plan
// (docs/mcgs-log.md, edges per visited node): 13 on average in 5 s
// searches without collections, 19-21 in middlegames, 3.6-5.5 in simple
// endgames, and 3-9 right after collections (pruned nodes keep their node
// but lose their edges). Over the 16 bench positions at 5 s and Hash 64,
// 8 gave 184 collections (main: 200), as few as 13 did, without 13's
// 2-3x more collections in the endgames (which fill the node arena first).
static constexpr size_t EDGES_PER_NODE = 8;
// Splits `bytes` between the node arena, the edge arena and the table.
void resize_bytes(size_t bytes);
// Empties the graph. The caller then creates the root and sets it.
void clear();
// A fresh node, or 0 when the node arena is full.
u32 alloc_node();
// The index of `count` fresh edges, or 0 when the edge arena is full.
u32 alloc_edges(u32 count);
void set_root(u32 idx) { root_ = idx; }
// The node of the position with this key and check, 0 when there is none.
u32 find(u64 key, u16 check) const;
// Enters a node, which must not be in the table yet, by its key.
void insert(u32 idx);
// Makes `new_root` the root. Nothing is moved or dropped: what the new
// root no longer reaches goes at the next collection. Returns the number
// of nodes in the graph.
size_t reroot(u32 new_root);
// Frees memory when an arena is full: the least visited parts of the graph
// are cut back to leaves until at most `keep_fraction` of each arena is in
// use. Returns the number of nodes kept.
size_t collect_garbage(double keep_fraction);
// The same with explicit targets (in slots, null slots included).
size_t collect_garbage(size_t node_target, size_t edge_target);
Node& node(u32 idx) { return nodes_[idx]; }
const Node& node(u32 idx) const { return nodes_[idx]; }
Edge& edge(u32 idx) { return edges_[idx]; }
const Edge& edge(u32 idx) const { return edges_[idx]; }
u32 root() const { return root_; }
size_t nodes_used() const { return nodes_used_; }
size_t edges_used() const { return edges_used_; }
size_t node_capacity() const { return nodes_.size(); }
size_t edge_capacity() const { return edges_.size(); }
size_t table_entries() const { return table_entries_; }
size_t table_slots() const { return table_.size(); }
// The node a table slot points to (0 = empty) and the key half it holds.
u32 table_node(size_t slot) const { return table_[slot].node; }
u32 table_key_hi(size_t slot) const { return table_[slot].key_hi; }
// How full the fuller arena is, per mille.
int fill_permille() const {
return int(std::max(nodes_used_ * 1000 / nodes_.size(), edges_used_ * 1000 / edges_.size()));
}
private:
// Open addressing with linear probing. The table has at least twice as
// many slots as the node arena has nodes, so it is never more than half
// full and needs no collection of its own. Nothing is deleted from it:
// after a collection or a reroot it is rebuilt from the surviving nodes.
struct Slot {
u32 key_hi = 0; // upper half of the key
u32 node = 0; // 0 = empty
};
static_assert(sizeof(Slot) == 8);
std::vector<Node> nodes_;
std::vector<Edge> edges_;
std::vector<Slot> table_;
size_t table_mask_ = 0;
size_t table_entries_ = 0;
size_t nodes_used_ = 0;
size_t edges_used_ = 0;
u32 root_ = 0;
// Keeps what is reachable from `new_root`, dropping the edges of every
// node with fewer than `min_visits` visits, packs both arenas to the
// front in place and rebuilds the table.
size_t compact(u32 new_root, u32 min_visits);
u32 prune_threshold(size_t node_target, size_t edge_target) const;
void rebuild_table();
};
// Butterfly history (after Vine, aronpetkovski.com/blog/butterfly-history-mcts):
// every playout scores each move on its path with the playout's result, and
// the score is added to the move's policy logit when a node is expanded.
class ButterflyHistory {
public:
// Value of a move's entry at which it shifts the policy logit by 1.
static constexpr float LOGIT_SCALE = 16384.0f;
void clear() { table_ = {}; }
int get(int stm, Move m) const { return table_[stm][m.from()][m.to()]; }
// `bonus` is the playout's result for the side that played `m`, in
// centipawns. Entries pull towards it and saturate near +-8192.
void update(int stm, Move m, int bonus) {
i16& entry = table_[stm][m.from()][m.to()];
const int v = entry + bonus - entry * std::abs(bonus) / 8192;
entry = i16(std::clamp(v, -32000, 32000));
}
private:
std::array<std::array<std::array<i16, 64>, 64>, 2> table_{};
};
struct SearchLimits {
u64 nodes = 0;
i64 movetime = 0;
i64 time[2] = {0, 0};
i64 inc[2] = {0, 0};
int movestogo = 0;
int depth = 0;
bool infinite = false;
};
struct SearchParams {
float cpuct = 1.60f;
// At the root: cpuct x 1.458, Monty's root_cpuct / cpuct (0.4119 / 0.2826).
float root_cpuct = 2.33f;
// cpuct is multiplied by 1 + ln((N + scale) / scale) for a node with N visits
// (Monty: 64 x 128).
float cpuct_visit_scale = 8192.0f;
float fpu_reduction = 0.30f;
float policy_temperature = 1.00f;
i64 move_overhead = 20;
};
struct SearchResult {
Move best;
u64 nodes = 0; // playouts
u64 tree_positions = 0; // positions visited across all playouts (bench signature)
i64 time_ms = 0;
};
class Searcher {
public:
SearchParams params;
std::atomic<bool> stop_flag{false};
// Coloured output for a human at a terminal instead of UCI info lines.
bool pretty = false;
Searcher();
void set_hash(size_t mb) {
// 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;
}
// Forget the previous tree, e.g. on ucinewgame.
void new_game() {
tree_valid_ = false;
butterfly_.clear();
}
// Synchronous search. `history` holds the keys of every position that led to
// `root`, including the key of `root` itself (for repetition detection).
SearchResult search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
bool print_info);
#ifdef RIGBY_VERIFY_TREE
// The `verify` command: incremental keys along random games, and garbage
// collection and rerooting against a snapshot of the tree. Aborts on a failure.
void self_test();
#endif
private:
using Clock = std::chrono::steady_clock;
Tree tree_;
// Kept between moves of a game, like the tree.
ButterflyHistory butterfly_;
Position root_pos_;
std::vector<u64> history_;
size_t root_history_size_ = 0;
// The nodes of a playout, from the root, and the edges it took
// (edge_path_[i] leaves path_[i]). A playout that ends in a draw of its
// path has one edge more than nodes before the draw.
std::vector<u32> path_;
std::vector<u32> edge_path_;
// Guards against a key collision linking positions into a loop that
// repetition detection cannot see. Real playouts end long before this.
static constexpr int MAX_PLAYOUT_DEPTH = 512;
// The previous search, kept so its tree can be reused.
bool tree_valid_ = false;
Position prev_root_;
std::vector<u64> prev_history_;
Clock::time_point start_time_;
i64 time_limit_ms_ = 0; // soft limit
i64 hard_limit_ms_ = 0;
static constexpr i64 HARD_LIMIT_FACTOR = 3;
// The limit comes from the game clock (not movetime), so stopping early saves time.
bool clock_search_ = false;
std::vector<u32> root_start_visits_;
// Lc0's default: the remaining playouts are divided by this before asking
// whether another root move could still overtake the best one.
static constexpr double SMART_PRUNING_FACTOR = 1.33;
u64 iterations_ = 0;
u64 depth_sum_ = 0;
int seldepth_ = 0;
bool gc_pending_ = false;
int gc_runs_ = 0;
size_t reused_ = 0;
u64 node_limit_ = 0;
pretty::LiveView live_;
// Share of the arena kept after a collection.
static constexpr double GC_KEEP_FRACTION = 0.5;
void playout();
// First visit of a position: a new node with one visit, entered into the
// table. Settles what the position itself decides (checkmate, stalemate,
// insufficient material except at the root), otherwise evaluates.
// `value` gets the result for the side to move. Returns 0 when the node
// arena is full.
u32 create_node(const Position& pos, bool is_root, float& value);
// Second visit: creates the edges with their priors. False when the
// arena is full (a collection is then scheduled).
bool expand(u32 idx, const Position& pos);
// The edge PUCT picks at node `idx`, 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 in the graph (some may no longer be
// reachable), 0 when nothing could be reused.
size_t reuse_tree(const Position& root);
// True when the root node's edges are exactly the legal moves of `root`.
bool root_edges_valid(const Position& root) const;
// Empties the graph, leaving an evaluated, unexpanded root for `root`.
void clear_tree(const Position& root);
#ifdef RIGBY_VERIFY_TREE
// Checks the graph from root_pos_; `history` ends with the root's key.
// `collected`: right after a collection, when every node must be reachable.
void verify_tree(const std::vector<u64>& history, bool collected = false) const;
#endif
void compute_time_limit(const SearchLimits& limits);
i64 elapsed_ms() const;
bool should_stop(const SearchLimits& limits) const;
bool best_move_settled(i64 ms, i64 limit_ms) const;
// The edge with the most visits at node `idx`, 0 when it has none.
u32 best_edge(u32 idx) const;
// Q of a visited edge from the view of the side choosing it: the child's
// Q, with draws of the path counted as 0.
float visited_edge_q(const Edge& e) const {
if (!e.draws) return tree_.node(e.child).q;
const u32 w = e.visits - e.draws;
return w ? float(w) / float(e.visits) * tree_.node(e.child).q : 0.0f;
}
// The same, 0 when the edge is unvisited.
float edge_q(const Edge& e) const { return e.visits ? visited_edge_q(e) : 0.0f; }
void print_info() const;
std::vector<Move> principal_variation() const;
void draw_dashboard(bool done);
};
} // namespace rigby
-998
View File
@@ -1,998 +0,0 @@
#include "mcts.h"
#include <algorithm>
#include <bit>
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <random>
#include <sstream>
#include <tuple>
#include "eval.h"
#include "pretty.h"
#include "uci_io.h"
namespace rigby {
// ---------------------------------------------------------------------------
// Tree
// ---------------------------------------------------------------------------
u16 position_check(const Position& pos) {
u64 x = pos.colors[WHITE] ^ std::rotl(pos.pieces[PAWN], 17) ^ std::rotl(pos.pieces[KING], 41);
// splitmix64's finaliser
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
return u16(x ^ (x >> 31));
}
void Tree::resize_bytes(size_t bytes) {
// A node costs its own 32 bytes plus EDGES_PER_NODE edges of 16.
const size_t per_node = sizeof(Node) + EDGES_PER_NODE * sizeof(Edge);
const size_t node_count = std::max<size_t>(bytes / per_node, 1024);
nodes_.assign(node_count, Node{});
nodes_.shrink_to_fit();
edges_.assign(node_count * EDGES_PER_NODE, Edge{});
edges_.shrink_to_fit();
clear();
}
void Tree::clear() {
nodes_used_ = 2; // index 0 is the null node, index 1 the root
edges_used_ = 1; // index 0 is the null edge
root_ = 1;
nodes_[root_] = Node{};
}
u32 Tree::alloc_node() {
if (nodes_used_ >= nodes_.size()) return 0;
return u32(nodes_used_++);
}
u32 Tree::alloc_edges(u32 count) {
if (edges_used_ + count > edges_.size()) return 0;
const u32 idx = u32(edges_used_);
edges_used_ += count;
return idx;
}
size_t Tree::reroot(u32 new_root) {
if (new_root == root_) return nodes_used_ - 1;
return compact(new_root, 0);
}
size_t Tree::collect_garbage(double keep_fraction) {
return collect_garbage(size_t(double(nodes_.size()) * keep_fraction), size_t(double(edges_.size()) * keep_fraction));
}
size_t Tree::collect_garbage(size_t node_target, size_t edge_target) {
return compact(root_, prune_threshold(node_target, edge_target));
}
u32 Tree::prune_threshold(size_t node_target, size_t edge_target) const {
// A node keeps its edges through a collection with threshold T when it has
// at least T visits, and the child nodes of those edges stay. Visits only
// shrink going down a tree, so every ancestor of such a node survives too,
// and the size kept for a threshold is just the edges and child nodes of
// all nodes with at least that many visits.
constexpr u32 CAP = 1 << 16;
std::vector<u64> edges_by_visits(CAP + 1, 0);
std::vector<u64> children_by_visits(CAP + 1, 0);
std::vector<u32> stack{root_};
while (!stack.empty()) {
const Node& node = nodes_[stack.back()];
stack.pop_back();
if (!node.first_edge) continue;
const u32 bucket = std::min(node.visits, CAP);
edges_by_visits[bucket] += node.num_edges;
for (u32 i = 0; i < node.num_edges; i++) {
const u32 child = edges_[node.first_edge + i].child;
if (!child) continue;
children_by_visits[bucket]++;
stack.push_back(child);
}
}
u64 kept_nodes = 2; // null node and root
u64 kept_edges = 1; // null edge
for (u32 v = CAP; v >= 1; v--) {
if (kept_nodes + children_by_visits[v] > node_target || kept_edges + edges_by_visits[v] > edge_target)
return v + 1;
kept_nodes += children_by_visits[v];
kept_edges += edges_by_visits[v];
}
return 1;
}
size_t Tree::compact(u32 new_root, u32 min_visits) {
// Mark: everything reachable from the new root stays. A node below the
// visit threshold loses its edges and becomes a leaf again; it keeps its
// visits and Q (also as u and base) and gets expanded anew if search
// comes back to it. `blocks` collects every edge block that stays, as
// (old first index, size).
std::vector<u8> marked(nodes_used_, 0);
std::vector<std::pair<u32, u32>> blocks;
std::vector<u32> stack{new_root};
marked[new_root] = 1;
while (!stack.empty()) {
const u32 idx = stack.back();
stack.pop_back();
Node& node = nodes_[idx];
if (!node.first_edge) continue;
if (idx != new_root && node.visits < min_visits) {
node.first_edge = 0;
node.num_edges = 0;
node.state = UNEXPANDED;
node.u = node.q;
node.base = node.visits;
continue;
}
blocks.emplace_back(node.first_edge, node.num_edges);
for (u32 i = 0; i < node.num_edges; i++) {
const u32 child = edges_[node.first_edge + i].child;
if (child && !marked[child]) {
marked[child] = 1;
stack.push_back(child);
}
}
}
// Forwarding: the marked nodes and the kept edge blocks get new places in
// their old index order. Every destination is then at or before its
// source, so both arenas can slide to the front in place, whatever order
// things were allocated in.
std::vector<u32> forward(nodes_used_, 0);
u32 next_node = 1;
for (u32 i = 1; i < nodes_used_; i++)
if (marked[i]) forward[i] = next_node++;
std::sort(blocks.begin(), blocks.end());
std::vector<u32> dest(blocks.size());
u32 next_edge = 1;
for (size_t i = 0; i < blocks.size(); i++) {
dest[i] = next_edge;
next_edge += blocks[i].second;
}
const auto remap_edges = [&](u32 old_first) -> u32 {
if (!old_first) return 0;
const auto it = std::lower_bound(blocks.begin(), blocks.end(), std::make_pair(old_first, u32(0)));
return dest[size_t(it - blocks.begin())];
};
for (u32 i = 1; i < nodes_used_; i++) {
if (!marked[i]) continue;
Node& node = nodes_[forward[i]];
if (forward[i] != i) node = nodes_[i];
node.first_edge = remap_edges(node.first_edge);
}
for (size_t i = 0; i < blocks.size(); i++) {
const auto [first, count] = blocks[i];
if (dest[i] != first) std::memmove(&edges_[dest[i]], &edges_[first], size_t(count) * sizeof(Edge));
for (u32 j = 0; j < count; j++) {
Edge& e = edges_[dest[i] + j];
e.child = forward[e.child];
}
}
root_ = forward[new_root];
nodes_used_ = next_node;
edges_used_ = next_edge;
return nodes_used_ - 1; // everything but the null node
}
// ---------------------------------------------------------------------------
// Searcher
// ---------------------------------------------------------------------------
Searcher::Searcher() { set_hash(64); }
void Searcher::clear_tree(const Position& root) {
tree_.clear();
Node& node = tree_.node(tree_.root());
node.key = root.key;
node.check = position_check(root);
}
i64 Searcher::elapsed_ms() const {
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time_).count();
}
void Searcher::compute_time_limit(const SearchLimits& limits) {
time_limit_ms_ = 0;
hard_limit_ms_ = 0;
clock_search_ = false;
if (limits.infinite) return;
if (limits.movetime) {
time_limit_ms_ = hard_limit_ms_ = std::max<i64>(1, limits.movetime - params.move_overhead);
return;
}
const int us = root_pos_.stm;
if (limits.time[us] <= 0) return;
const i64 remaining = std::max<i64>(1, limits.time[us] - params.move_overhead);
const i64 moves_left = limits.movestogo ? std::min(limits.movestogo, 40) : 25;
const i64 target = remaining / moves_left + limits.inc[us] * 3 / 4;
time_limit_ms_ = std::clamp<i64>(target, 1, remaining / 2 + 1);
// A move that is still open at the soft limit may run on up to this.
hard_limit_ms_ = std::max(time_limit_ms_, std::min(time_limit_ms_ * HARD_LIMIT_FACTOR, remaining / 3));
clock_search_ = true;
}
bool Searcher::best_move_settled(i64 ms, i64 limit_ms) const {
// Smart pruning (Lc0): stop when no other root move can catch up with the
// leading one in the playouts the remaining time still allows, at the
// speed so far, scaled down by SMART_PRUNING_FACTOR. Only the visits of
// this search count: a reused tree often brings the best move so many
// visits that nothing could overtake it, which would stop every search
// at once. The move leading this search must also be the one played.
if (ms <= 0 || iterations_ < 256) return false;
const Node& root = tree_.node(tree_.root());
if (root_start_visits_.size() != root.num_edges) return false;
u32 first = 0, second = 0, leader = 0;
for (u32 i = 0; i < root.num_edges; i++) {
const u32 v = tree_.edge(root.first_edge + i).visits - root_start_visits_[i];
if (v > first) {
second = first;
first = v;
leader = root.first_edge + i;
} else if (v > second) {
second = v;
}
}
if (leader != best_edge(tree_.root())) return false;
const double remaining =
double(iterations_) / double(ms) * double(limit_ms - ms) / SMART_PRUNING_FACTOR;
return double(second) + remaining < double(first);
}
bool Searcher::should_stop(const SearchLimits& limits) const {
if (stop_flag.load(std::memory_order_relaxed)) return true;
if (limits.nodes && iterations_ >= limits.nodes) return true;
if (limits.depth && iterations_) {
// "depth" is the mean playout depth. Solved positions may never get
// there, so a depth limit also carries a generous playout cap.
if (int(depth_sum_ / iterations_) >= limits.depth) return true;
if (iterations_ >= (u64(1000) << std::min(2 * limits.depth, 14))) return true;
}
// The clock is cheap but not free; look at it every 64 playouts.
if (time_limit_ms_ && (iterations_ & 63) == 0) {
const i64 ms = elapsed_ms();
if (ms >= hard_limit_ms_) return true;
// Under a game clock the time saved on a settled move goes to later
// moves. A move that is not settled by the soft limit (time_limit_ms_)
// is an open one: it searches on until it settles against the hard
// limit or reaches it. Other limits stop at the soft limit, which is
// also their hard one.
const bool extended = ms >= time_limit_ms_;
if (clock_search_ && best_move_settled(ms, extended ? hard_limit_ms_ : time_limit_ms_)) return true;
}
return false;
}
bool Searcher::is_repetition(const Position& pos) const {
// history_.back() is the key of `pos` itself. Any earlier occurrence with the
// same side to move inside the reversible window counts as a draw (two-fold).
const int n = int(history_.size());
for (int back = 4; back <= pos.halfmove && back < n; back += 2)
if (history_[n - 1 - back] == pos.key) return true;
return false;
}
size_t Searcher::reuse_tree(const Position& root) {
// The new game history must continue the previous one; the keys after the
// old root are the positions reached by the moves played since.
if (!tree_valid_ || history_.size() < prev_history_.size() ||
!std::equal(prev_history_.begin(), prev_history_.end(), history_.begin()))
return 0;
u32 idx = tree_.root();
Position pos = prev_root_;
for (size_t i = prev_history_.size(); i < history_.size(); i++) {
const Node& node = tree_.node(idx);
if (node.state != EXPANDED) return 0;
u32 next = 0;
for (u32 c = 0; c < node.num_edges && !next; c++) {
const Edge& e = tree_.edge(node.first_edge + c);
Position child = pos;
child.make_move(Move::from_raw(e.move));
if (child.key == history_[i]) {
// A move search never tried has no node to continue from.
if (!e.child) return 0;
next = e.child;
pos = child;
}
}
if (!next) return 0;
idx = next;
}
// A node that was a draw by repetition or the 50-move rule inside the old
// tree can be a real position to play from now; start such a root afresh.
if (pos.key != root.key || tree_.node(idx).state != EXPANDED) return 0;
return tree_.reroot(idx);
}
#ifdef RIGBY_VERIFY_TREE
// Debug check, from the root as `root_pos_` with the game history `history`
// (ending with the root's key):
// - every node is reached exactly once (in-degree 1, the root 0), and the
// arenas hold nothing else;
// - a node's key and check match its position, and its state is the one
// evaluate_leaf gives that position on this path;
// - an expanded node has one edge per legal move;
// - an edge has a child node exactly when it has visits, with as many visits
// as the child (a tree), and no draws yet;
// - every expanded node has at least one visit more than its edges together
// (more when it was evaluated as a leaf while the tree was full); the root
// is expanded before its first visit, so it may have exactly as many;
// - Q and u are finite and in [-1, 1].
void Searcher::verify_tree(const std::vector<u64>& history) const {
const auto fail = [&](u32 idx, const Position& pos, const std::string& what) {
const Node& n = tree_.node(idx);
std::cerr << "TREE CORRUPT at node " << idx << " (" << pos.fen() << "): " << what << " visits=" << n.visits
<< " q=" << n.q << " state=" << int(n.state) << " edges=" << int(n.num_edges)
<< " first=" << n.first_edge << " nodes_used=" << tree_.nodes_used()
<< " edges_used=" << tree_.edges_used() << std::endl;
std::abort();
};
std::vector<u32> in_degree(tree_.nodes_used(), 0);
std::vector<u64> keys = history;
struct Frame {
u32 idx;
Position pos;
int depth;
u32 next = 0;
};
std::vector<Frame> stack;
u64 nodes = 0, edges = 0;
const auto enter = [&](u32 idx, const Position& pos, int depth) {
const Node& node = tree_.node(idx);
nodes++;
if (node.key != pos.key || node.check != position_check(pos)) fail(idx, pos, "key or check mismatch");
if (!std::isfinite(node.q) || std::abs(node.q) > 1.0f || !std::isfinite(node.u) || std::abs(node.u) > 1.0f)
fail(idx, pos, "q or u out of range");
// The state evaluate_leaf gives this position on this path.
MoveList legal;
generate_legal(pos, legal);
int expected = -1; // not terminal
if (legal.empty()) {
expected = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
} else if (depth > 0) {
bool repetition = false;
const int n = int(keys.size());
for (int back = 4; back <= pos.halfmove && back < n; back += 2)
if (keys[n - 1 - back] == pos.key) repetition = true;
if (pos.halfmove >= 100 || pos.insufficient_material() || repetition) expected = TERMINAL_DRAW;
}
if (expected >= 0 ? node.state != expected : node.state != UNEXPANDED && node.state != EXPANDED)
fail(idx, pos, "state " + std::to_string(node.state) + " expected " + std::to_string(expected));
if (node.state != EXPANDED) {
if (node.first_edge || node.num_edges) fail(idx, pos, "edges on a node that is not expanded");
} else {
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()));
bool seen[256] = {};
u64 edge_visits = 0;
for (u32 i = 0; i < node.num_edges; i++) {
const Edge& e = tree_.edge(node.first_edge + i);
const auto it = std::find(legal.begin(), legal.end(), Move::from_raw(e.move));
if (it == legal.end() || seen[it - legal.begin()]) fail(idx, pos, "illegal or repeated edge move");
seen[it - legal.begin()] = true;
if (e.draws) fail(idx, pos, "edge with draws");
if (e.child >= tree_.nodes_used()) fail(idx, pos, "edge child out of range");
if (bool(e.child) != bool(e.visits)) fail(idx, pos, "edge child without visits or the reverse");
if (e.child && e.visits != tree_.node(e.child).visits) fail(idx, pos, "edge and child visits differ");
if (e.child && ++in_degree[e.child] != 1) fail(idx, pos, "node reached twice");
edge_visits += e.visits;
}
edges += node.num_edges;
if (node.visits < edge_visits + (idx == tree_.root() ? 0 : 1))
fail(idx, pos, "fewer visits than the edges, edge visits " + std::to_string(edge_visits));
}
stack.push_back({idx, pos, depth});
};
if (tree_.root() == 0 || tree_.root() >= tree_.nodes_used()) fail(tree_.root(), root_pos_, "bad root index");
enter(tree_.root(), root_pos_, 0);
while (!stack.empty()) {
Frame& f = stack.back();
const Node& node = tree_.node(f.idx);
if (f.next < node.num_edges) {
const Edge& e = tree_.edge(node.first_edge + f.next++);
if (!e.child) continue;
Position next = f.pos;
next.make_move(Move::from_raw(e.move));
keys.push_back(next.key);
const int depth = f.depth + 1;
enter(e.child, next, depth); // invalidates f
} else {
stack.pop_back();
if (!stack.empty()) keys.pop_back();
}
}
if (nodes != tree_.nodes_used() - 1 || edges != tree_.edges_used() - 1)
fail(tree_.root(), root_pos_,
"unreachable nodes or edges: reached " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges");
uci_io::send("info string tree verified: " + std::to_string(nodes) + " nodes, " + std::to_string(edges) +
" edges");
}
#endif
float Searcher::evaluate_leaf(u32 idx, const Position& pos, int depth) {
Node& node = tree_.node(idx);
MoveList moves;
generate_legal(pos, moves);
if (moves.empty()) {
node.state = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
return node.state == TERMINAL_LOSS ? -1.0f : 0.0f;
}
// The root must always produce a move, so it is never declared drawn.
if (depth > 0 && (pos.halfmove >= 100 || pos.insufficient_material() || is_repetition(pos))) {
node.state = TERMINAL_DRAW;
return 0.0f;
}
// A position searched before (a transposition, or from an earlier search)
// brings its Q along.
if (float q; value_hash_.probe(pos.key, q)) return q;
return eval::value(pos);
}
bool Searcher::expand(u32 idx, const Position& pos) {
MoveList moves;
generate_legal(pos, moves);
const u32 first = tree_.alloc_edges(u32(moves.size()));
if (!first) {
// Out of memory: this time the node stays a leaf; the tree is collected
// right after this playout, so the next visit can expand it.
gc_pending_ = true;
return false;
}
// The butterfly history of each move shifts its logit. The priors are a
// snapshot: later history updates do not change them.
float bias[256];
for (int i = 0; i < moves.size(); i++)
bias[i] = float(butterfly_.get(pos.stm, moves[i])) / ButterflyHistory::LOGIT_SCALE;
float priors[256];
eval::policy(pos, moves, params.policy_temperature, bias, priors);
for (int i = 0; i < moves.size(); i++) {
Edge& e = tree_.edge(first + u32(i));
e = Edge{};
e.move = moves[i].raw();
e.policy = u16(std::lround(std::clamp(priors[i], 0.0f, 1.0f) * 65535.0f));
}
Node& node = tree_.node(idx);
node.first_edge = first;
node.num_edges = u8(moves.size());
node.state = EXPANDED;
return true;
}
u32 Searcher::select_edge(u32 idx) const {
const Node& node = tree_.node(idx);
// node.q is from the view of the side that moved into this node, so the side
// to move here sees -q.
const float parent_q = node.visits ? -node.q : 0.0f;
float visited_policy = 0.0f;
for (u32 i = 0; i < node.num_edges; i++) {
const Edge& e = tree_.edge(node.first_edge + i);
if (e.visits) visited_policy += e.prior();
}
const float fpu = parent_q - params.fpu_reduction * std::sqrt(visited_policy);
// Exploration grows with the visits (Monty's scaling): a node searched a
// lot keeps giving its other moves a chance.
const float n = float(std::max<u32>(node.visits, 1));
// The root, where the move is chosen, explores more.
const float base_cpuct = idx == tree_.root() ? params.root_cpuct : params.cpuct;
const float cpuct = base_cpuct * (1.0f + std::log((n + params.cpuct_visit_scale) / params.cpuct_visit_scale));
const float explore = cpuct * std::sqrt(n);
u32 best = node.first_edge;
float best_score = -1e30f;
for (u32 i = 0; i < node.num_edges; i++) {
const u32 c = node.first_edge + i;
const Edge& e = tree_.edge(c);
// The child's Q is from the view of the side to move here.
const float q = e.visits ? tree_.node(e.child).q : fpu;
const float score = q + explore * e.prior() / float(1 + e.visits);
if (score > best_score) {
best_score = score;
best = c;
}
}
return best;
}
void Searcher::playout() {
Position pos = root_pos_;
history_.resize(root_history_size_);
path_.clear();
edge_path_.clear();
u32 idx = tree_.root();
path_.push_back(idx);
int depth = 0;
float value;
for (;;) {
const Node& node = tree_.node(idx);
if (node.state == TERMINAL_LOSS) {
value = -1.0f;
break;
}
if (node.state == TERMINAL_DRAW) {
value = 0.0f;
break;
}
if (node.state == UNEXPANDED) {
// Most leaves are only ever visited once, so a first visit just
// evaluates; edges (moves, priors, memory) come on the second.
if (node.visits == 0) {
value = evaluate_leaf(idx, pos, depth);
break;
}
if (!expand(idx, pos)) {
value = eval::value(pos);
break;
}
}
const u32 e = select_edge(idx);
Edge& edge = tree_.edge(e);
u32 child = edge.child;
const bool created = !child;
if (created) {
// The first time this move is chosen: its node is created now and
// evaluated on this visit.
child = tree_.alloc_node();
if (!child) {
// The node arena is full: as when expansion fails, this node
// takes the playout and the tree is collected right after.
gc_pending_ = true;
value = eval::value(pos);
break;
}
edge.child = child;
}
pos.make_move(Move::from_raw(edge.move));
if (created) {
Node& fresh = tree_.node(child);
fresh = Node{};
fresh.key = pos.key;
fresh.check = position_check(pos);
}
history_.push_back(pos.key);
path_.push_back(child);
edge_path_.push_back(e);
idx = child;
depth++;
}
// `value` is from the view of the side to move at the leaf. Each node stores
// the view of the side that moved into it, so flip before every update.
// The same result in centipawns scores the move into each node in the
// butterfly history, for the side that played it (the side to move at the
// parent, depth i - 1). Edge visits are kept equal to the child's.
int bonus = eval::q_to_cp(std::clamp(value, -0.998f, 0.998f));
for (size_t i = path_.size(); i-- > 0;) {
value = -value;
bonus = -bonus;
Node& node = tree_.node(path_[i]);
node.visits++;
node.q += (value - node.q) / float(node.visits);
// The Q from the view of the side to move at the node. Draws by
// repetition or the 50-move rule belong to the path, not the position.
if (node.state != TERMINAL_DRAW) value_hash_.store(history_[root_history_size_ - 1 + i], -node.q, node.visits);
if (i) {
Edge& e = tree_.edge(edge_path_[i - 1]);
e.visits++;
butterfly_.update(root_pos_.stm ^ int((i - 1) & 1), Move::from_raw(e.move), bonus);
}
}
iterations_++;
depth_sum_ += u64(depth);
seldepth_ = std::max(seldepth_, depth);
}
u32 Searcher::best_edge(u32 idx) const {
const Node& node = tree_.node(idx);
u32 best = 0;
for (u32 i = 0; i < node.num_edges; i++) {
const u32 c = node.first_edge + i;
if (!best) {
best = c;
continue;
}
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)
best = c;
}
return best;
}
void Searcher::print_info() const {
const Node& root = tree_.node(tree_.root());
const i64 ms = elapsed_ms();
const u32 best = best_edge(tree_.root());
std::ostringstream out;
out << "info depth " << (iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0) << " seldepth "
<< seldepth_;
const float q = best && tree_.edge(best).visits ? edge_q(tree_.edge(best)) : -root.q;
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();
out << " pv";
for (const Move m : principal_variation()) out << ' ' << root_pos_.uci(m);
uci_io::send(out.str());
}
std::vector<Move> Searcher::principal_variation() const {
std::vector<Move> pv;
u32 idx = tree_.root();
for (int ply = 0; ply < 64; ply++) {
const u32 c = best_edge(idx);
if (!c || !tree_.edge(c).visits) break;
pv.push_back(Move::from_raw(tree_.edge(c).move));
idx = tree_.edge(c).child;
}
return pv;
}
void Searcher::draw_dashboard(bool done) {
const Node& root = tree_.node(tree_.root());
const u32 best = best_edge(tree_.root());
const i64 ms = elapsed_ms();
pretty::Dashboard d;
d.root = root_pos_;
d.depth = int(iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0);
d.seldepth = seldepth_;
d.playouts = iterations_;
d.nps = ms ? iterations_ * 1000 / u64(ms) : iterations_;
d.ms = ms;
d.time_limit_ms = time_limit_ms_;
d.node_limit = node_limit_;
d.hashfull = tree_.fill_permille();
d.cp = eval::q_to_cp(best && tree_.edge(best).visits ? edge_q(tree_.edge(best)) : -root.q);
d.pv = principal_variation();
for (u32 i = 0; i < root.num_edges; i++) {
const Edge& e = tree_.edge(root.first_edge + i);
d.moves.push_back({Move::from_raw(e.move), e.visits, eval::q_to_cp(edge_q(e)), e.prior()});
}
d.reused = reused_;
d.collections = gc_runs_;
d.done = done;
uci_io::send(live_.draw(d));
}
SearchResult Searcher::search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
bool print) {
start_time_ = Clock::now();
root_pos_ = root;
history_ = history;
if (history_.empty() || history_.back() != root.key) history_.push_back(root.key);
root_history_size_ = history_.size();
#ifdef RIGBY_VERIFY_TREE
// Check the previous tree as the last search left it, and again after rerooting.
if (tree_valid_ && history_.size() >= prev_history_.size()) {
root_pos_ = prev_root_;
verify_tree(prev_history_);
root_pos_ = root;
}
#endif
const size_t reused = reuse_tree(root);
if (!reused) clear_tree(root);
#ifdef RIGBY_VERIFY_TREE
if (reused) verify_tree(history_);
#endif
if (print && !pretty && reused) uci_io::send("info string reused " + std::to_string(reused) + " nodes");
iterations_ = 0;
depth_sum_ = 0;
seldepth_ = 0;
gc_pending_ = false;
gc_runs_ = 0;
reused_ = reused;
node_limit_ = limits.nodes;
compute_time_limit(limits);
SearchResult result;
MoveList root_moves;
generate_legal(root, root_moves);
if (root_moves.empty()) {
tree_valid_ = false;
if (print && pretty)
uci_io::send(pretty::note(root.in_check() ? "checkmate, no legal moves" : "stalemate, no legal moves"));
else if (print)
uci_io::send("info depth 0 score " + std::string(root.in_check() ? "mate 0" : "cp 0"));
return result;
}
if (print && pretty) live_.begin();
// The root needs its children 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)) {
clear_tree(root);
gc_pending_ = false;
expand(tree_.root(), root);
}
// Root move visits brought along by tree reuse, for smart pruning. The
// root's edges keep their order through collections.
root_start_visits_.clear();
{
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);
}
// UCI reports once a second; the dashboard for a human is redrawn in place
// ten times a second.
const i64 info_interval = pretty ? 100 : 1000;
const u64 info_mask = pretty ? 255 : 1023;
i64 next_info = pretty ? 0 : 1000;
do {
playout();
if (gc_pending_) {
tree_.collect_garbage(GC_KEEP_FRACTION);
gc_pending_ = false;
gc_runs_++;
#ifdef RIGBY_VERIFY_TREE
verify_tree(std::vector<u64>(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)));
#endif
}
if (print && (iterations_ & info_mask) == 0) {
const i64 ms = elapsed_ms();
if (ms >= next_info) {
next_info = ms + info_interval;
if (pretty) draw_dashboard(false);
else print_info();
}
}
} while (!should_stop(limits));
if (print && pretty) {
draw_dashboard(true);
} else if (print) {
print_info();
if (gc_runs_) uci_io::send("info string tree collected " + std::to_string(gc_runs_) + " times");
}
#ifdef RIGBY_VERIFY_TREE
verify_tree(std::vector<u64>(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_)));
#endif
const u32 best = best_edge(tree_.root());
result.best = Move::from_raw(tree_.edge(best).move);
result.nodes = iterations_;
result.tree_positions = iterations_ + depth_sum_;
result.time_ms = elapsed_ms();
tree_valid_ = true;
prev_root_ = root;
prev_history_.assign(history_.begin(), history_.begin() + std::ptrdiff_t(root_history_size_));
return result;
}
#ifdef RIGBY_VERIFY_TREE
namespace {
[[noreturn]] void self_test_failed(const std::string& what) {
std::cerr << "VERIFY FAILED: " << what << std::endl;
std::abort();
}
// What a node looked like, to compare after a collection or a reroot.
struct NodeSnapshot {
u64 key;
u32 visits;
float q, u;
u32 base;
u8 state;
u16 check;
// (move, policy, visits, draws, has a child) per edge
std::vector<std::tuple<u16, u16, u32, u32, bool>> edges;
};
using MovePath = std::vector<u16>;
} // namespace
void Searcher::self_test() {
// (a) The incremental key equals the key of the same position set up from
// its FEN, along random games, standard and Chess960.
{
static constexpr const char* FENS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"rnbqkbnr/ppp1p1pp/8/3pPp2/8/8/PPPP1PPP/RNBQKBNR w KQkq f6 0 3",
"bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9",
"2nnrbkr/p1qppppp/8/1ppb4/6PP/3PP3/PPP2P2/BQNNRBKR w HEhe - 1 9",
"qrbnnkrb/pppppppp/8/8/8/8/PPPPPPPP/QRBNNKRB w GBgb - 0 1",
"rkrnnqbb/pppppppp/8/8/8/8/PPPPPPPP/RKRNNQBB w CAca - 0 1",
};
std::mt19937_64 rng(20261116);
u64 plies = 0;
for (const char* fen : FENS) {
for (int game = 0; game < 50; game++) {
Position pos;
if (!pos.set_fen(fen)) self_test_failed(std::string("bad fen ") + fen);
for (int ply = 0; ply < 300; ply++) {
MoveList moves;
generate_legal(pos, moves);
if (moves.empty()) break;
const Move m = moves[int(rng() % u64(moves.size()))];
const std::string before = pos.fen();
pos.make_move(m);
Position fresh;
if (!fresh.set_fen(pos.fen())) self_test_failed("fen does not parse: " + pos.fen());
if (fresh.key != pos.key || position_check(fresh) != position_check(pos))
self_test_failed("incremental key differs after " + before + " " + pos.uci(m) + " -> " +
pos.fen());
plies++;
}
}
}
uci_io::send("info string verify (a) keys: " + std::to_string(plies) + " plies ok");
}
// (b) Garbage collection and rerooting keep everything they keep exactly.
const auto snapshot = [&](u32 from) {
std::map<MovePath, NodeSnapshot> snap;
std::vector<std::pair<u32, MovePath>> stack{{from, {}}};
while (!stack.empty()) {
auto [idx, path] = stack.back();
stack.pop_back();
const Node& n = tree_.node(idx);
NodeSnapshot s{n.key, n.visits, n.q, n.u, n.base, n.state, n.check, {}};
for (u32 i = 0; i < n.num_edges; i++) {
const Edge& e = tree_.edge(n.first_edge + i);
s.edges.emplace_back(e.move, e.policy, e.visits, e.draws, e.child != 0);
if (e.child) {
MovePath next = path;
next.push_back(e.move);
stack.push_back({e.child, next});
}
}
snap.emplace(path, std::move(s));
}
return snap;
};
// Walks the current tree from the root and compares it with `before`.
// Returns the number of nodes; `pruned_max` / `kept_min` get the largest
// visits of a node that lost its edges and the smallest of a non-root node
// that kept them.
const auto compare = [&](const std::map<MovePath, NodeSnapshot>& before, bool allow_pruning, u32& pruned_max,
u32& kept_min) {
size_t count = 0;
pruned_max = 0;
kept_min = ~0u;
std::vector<std::pair<u32, MovePath>> stack{{tree_.root(), {}}};
while (!stack.empty()) {
auto [idx, path] = stack.back();
stack.pop_back();
count++;
const Node& n = tree_.node(idx);
const auto it = before.find(path);
if (it == before.end()) self_test_failed("a node appeared from nowhere");
const NodeSnapshot& s = it->second;
if (n.key != s.key || n.check != s.check || n.visits != s.visits || n.q != s.q)
self_test_failed("node changed (key, visits or q)");
if (!s.edges.empty() && !n.num_edges) {
if (!allow_pruning) self_test_failed("a node lost its edges in a reroot");
if (n.state != UNEXPANDED || n.first_edge || n.u != n.q || n.base != n.visits)
self_test_failed("pruned node not reset properly");
pruned_max = std::max(pruned_max, n.visits);
continue;
}
if (n.state != s.state || n.u != s.u || n.base != s.base || n.num_edges != s.edges.size())
self_test_failed("node changed (state, u, base or edges)");
if (n.num_edges && !path.empty()) kept_min = std::min(kept_min, n.visits);
for (u32 i = 0; i < n.num_edges; i++) {
const Edge& e = tree_.edge(n.first_edge + i);
if (std::make_tuple(e.move, e.policy, e.visits, e.draws, e.child != 0) != s.edges[i])
self_test_failed("edge changed");
if (e.child) {
MovePath next = path;
next.push_back(e.move);
stack.push_back({e.child, next});
}
}
}
return count;
};
static constexpr const char* SEARCH_FENS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r1bq1rk1/ppp2ppp/2np1n2/2b1p3/2B1P3/2NP1N2/PPP2PPP/R1BQ1RK1 w - - 0 7",
"8/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1",
"bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9",
};
for (const char* fen : SEARCH_FENS) {
Position root;
root.set_fen(fen);
SearchLimits limits;
limits.nodes = 30000;
// Collections down to a half, a quarter and an eighth of the tree.
new_game();
stop_flag = false;
search(root, {root.key}, limits, false);
for (int round = 1; round <= 3; round++) {
const auto before = snapshot(tree_.root());
const size_t node_target = tree_.nodes_used() >> round, edge_target = tree_.edges_used() >> round;
tree_.collect_garbage(node_target, edge_target);
if (tree_.nodes_used() > node_target || tree_.edges_used() > edge_target)
self_test_failed("collection kept more than its target");
u32 pruned_max, kept_min;
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});
uci_io::send("info string verify (b) gc " + std::string(fen) + ": " + std::to_string(before.size()) +
" -> " + std::to_string(count) + " nodes ok");
}
// Reroot two plies down the most visited line, as between two moves of a game.
new_game();
stop_flag = false;
search(root, {root.key}, limits, false);
std::vector<u64> history{root.key};
Position pos = root;
u32 idx = tree_.root();
for (int ply = 0; ply < 2; ply++) {
const u32 e = best_edge(idx);
if (!e || !tree_.edge(e).child) break;
pos.make_move(Move::from_raw(tree_.edge(e).move));
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");
const auto before = snapshot(idx);
tree_.reroot(idx);
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");
root_pos_ = pos;
verify_tree(history);
uci_io::send("info string verify (b) reroot " + std::string(fen) + ": " + std::to_string(count) +
" nodes ok");
}
new_game();
uci_io::send("info string verify passed");
}
#endif
} // namespace rigby
-311
View File
@@ -1,311 +0,0 @@
#pragma once
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <vector>
#include "position.h"
#include "pretty.h"
namespace rigby {
enum NodeState : u8 {
UNEXPANDED = 0,
EXPANDED,
TERMINAL_LOSS, // side to move is checkmated
TERMINAL_DRAW,
};
// A move out of a node. A node's edges sit next to each other in the edge
// arena, so the node only needs the index of the first one. The child node is
// created the first time search selects the edge.
struct Edge {
u32 child = 0; // node index, 0 = no node yet
u32 visits = 0; // how often search chose this move here (equals the child's visits in a tree)
u32 draws = 0; // of those, playouts that ended in a draw of the path (unused while the search is a tree)
u16 move = 0;
u16 policy = 0; // prior scaled to 0..65535
float prior() const { return float(policy) * (1.0f / 65535.0f); }
};
static_assert(sizeof(Edge) == 16);
// A position, created when search first reaches it.
struct Node {
u64 key = 0; // Zobrist key of the position
u32 first_edge = 0; // 0 = not expanded
u32 visits = 0;
float q = 0.0f; // running mean, from the view of the side that moved into the node
// `u` and `base` are set by garbage collection (the Q and visits a pruned
// node keeps) but not read yet. `check` is a second fingerprint of the
// position (see position_check). All three are for graph search.
float u = 0.0f;
u32 base = 0;
u8 num_edges = 0;
u8 state = UNEXPANDED;
u16 check = 0;
};
static_assert(sizeof(Node) == 32);
// A 16-bit fingerprint of the position that does not depend on the Zobrist keys.
u16 position_check(const Position& pos);
// Two arenas: nodes and edges. Index 0 of each is null.
class Tree {
public:
// Edges per node the arenas are sized for: the edge arena gets 128 of
// every 160 bytes, the node arena 32. Measured in step 1 of the MCGS plan
// (docs/mcgs-log.md, edges per visited node): 13 on average in 5 s
// searches without collections, 19-21 in middlegames, 3.6-5.5 in simple
// endgames, and 3-9 right after collections (pruned nodes keep their node
// but lose their edges). Over the 16 bench positions at 5 s and Hash 64,
// 8 gave 184 collections (main: 200), as few as 13 did, without 13's
// 2-3x more collections in the endgames (which fill the node arena first).
static constexpr size_t EDGES_PER_NODE = 8;
void resize_bytes(size_t bytes);
void clear();
// A fresh node, or 0 when the node arena is full.
u32 alloc_node();
// The index of `count` fresh edges, or 0 when the edge arena is full.
u32 alloc_edges(u32 count);
// Makes `new_root` the root and packs its subtree to the front of the
// arenas; everything else is dropped. Returns the number of nodes kept.
size_t reroot(u32 new_root);
// Frees memory when an arena is full: the least visited parts of the tree
// are cut back to leaves until at most `keep_fraction` of each arena is in
// use. Returns the number of nodes kept.
size_t collect_garbage(double keep_fraction);
// The same with explicit targets (in slots, null slots included).
size_t collect_garbage(size_t node_target, size_t edge_target);
Node& node(u32 idx) { return nodes_[idx]; }
const Node& node(u32 idx) const { return nodes_[idx]; }
Edge& edge(u32 idx) { return edges_[idx]; }
const Edge& edge(u32 idx) const { return edges_[idx]; }
u32 root() const { return root_; }
size_t nodes_used() const { return nodes_used_; }
size_t edges_used() const { return edges_used_; }
size_t node_capacity() const { return nodes_.size(); }
size_t edge_capacity() const { return edges_.size(); }
// How full the fuller arena is, per mille.
int fill_permille() const {
return int(std::max(nodes_used_ * 1000 / nodes_.size(), edges_used_ * 1000 / edges_.size()));
}
private:
std::vector<Node> nodes_;
std::vector<Edge> edges_;
size_t nodes_used_ = 0;
size_t edges_used_ = 0;
u32 root_ = 1;
// Keeps what is reachable from `new_root`, dropping the edges of every
// node with fewer than `min_visits` visits, and packs both arenas to the
// front in place.
size_t compact(u32 new_root, u32 min_visits);
u32 prune_threshold(size_t node_target, size_t edge_target) const;
};
// Butterfly history for MCTS (after Vine, aronpetkovski.com/blog/butterfly-history-mcts):
// every playout scores each move on its path with the playout's result, and
// the score is added to the move's policy logit when a node is expanded.
class ButterflyHistory {
public:
// Value of a move's entry at which it shifts the policy logit by 1.
static constexpr float LOGIT_SCALE = 16384.0f;
void clear() { table_ = {}; }
int get(int stm, Move m) const { return table_[stm][m.from()][m.to()]; }
// `bonus` is the playout's result for the side that played `m`, in
// centipawns. Entries pull towards it and saturate near +-8192.
void update(int stm, Move m, int bonus) {
i16& entry = table_[stm][m.from()][m.to()];
const int v = entry + bonus - entry * std::abs(bonus) / 8192;
entry = i16(std::clamp(v, -32000, 32000));
}
private:
std::array<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;
i64 time[2] = {0, 0};
i64 inc[2] = {0, 0};
int movestogo = 0;
int depth = 0;
bool infinite = false;
};
struct SearchParams {
float cpuct = 1.60f;
// At the root: cpuct x 1.458, Monty's root_cpuct / cpuct (0.4119 / 0.2826).
float root_cpuct = 2.33f;
// cpuct is multiplied by 1 + ln((N + scale) / scale) for a node with N visits
// (Monty: 64 x 128).
float cpuct_visit_scale = 8192.0f;
float fpu_reduction = 0.30f;
float policy_temperature = 1.00f;
i64 move_overhead = 20;
};
struct SearchResult {
Move best;
u64 nodes = 0; // playouts
u64 tree_positions = 0; // positions visited across all playouts (bench signature)
i64 time_ms = 0;
};
class Searcher {
public:
SearchParams params;
std::atomic<bool> stop_flag{false};
// Coloured output for a human at a terminal instead of UCI info lines.
bool pretty = false;
Searcher();
void set_hash(size_t mb) {
// A 32nd of the memory goes to the value hash, the rest to the tree
// (split between its arenas by Tree::EDGES_PER_NODE).
const size_t bytes = mb * 1024 * 1024;
value_hash_.resize(bytes / 32 / ValueHash::ENTRY_BYTES);
tree_.resize_bytes(bytes - bytes / 32);
tree_valid_ = false;
}
// Forget the previous tree, e.g. on ucinewgame.
void new_game() {
tree_valid_ = false;
butterfly_.clear();
value_hash_.clear();
}
// Synchronous search. `history` holds the keys of every position that led to
// `root`, including the key of `root` itself (for repetition detection).
SearchResult search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
bool print_info);
#ifdef RIGBY_VERIFY_TREE
// The `verify` command: incremental keys along random games, and garbage
// collection and rerooting against a snapshot of the tree. Aborts on a failure.
void self_test();
#endif
private:
using Clock = std::chrono::steady_clock;
Tree tree_;
// Kept between moves of a game, like the tree.
ButterflyHistory butterfly_;
Position root_pos_;
ValueHash value_hash_;
std::vector<u64> history_;
size_t root_history_size_ = 0;
// The nodes of a playout, from the root, and the edges between them
// (edge_path_[i] leads from path_[i] to path_[i + 1]).
std::vector<u32> path_;
std::vector<u32> edge_path_;
// The previous search, kept so its tree can be reused.
bool tree_valid_ = false;
Position prev_root_;
std::vector<u64> prev_history_;
Clock::time_point start_time_;
i64 time_limit_ms_ = 0; // soft limit
i64 hard_limit_ms_ = 0;
static constexpr i64 HARD_LIMIT_FACTOR = 3;
// The limit comes from the game clock (not movetime), so stopping early saves time.
bool clock_search_ = false;
std::vector<u32> root_start_visits_;
// Lc0's default: the remaining playouts are divided by this before asking
// whether another root move could still overtake the best one.
static constexpr double SMART_PRUNING_FACTOR = 1.33;
u64 iterations_ = 0;
u64 depth_sum_ = 0;
int seldepth_ = 0;
bool gc_pending_ = false;
int gc_runs_ = 0;
size_t reused_ = 0;
u64 node_limit_ = 0;
pretty::LiveView live_;
// Share of the arena kept after a collection.
static constexpr double GC_KEEP_FRACTION = 0.5;
void playout();
// First visit of a node: settles terminal states, otherwise evaluates.
float evaluate_leaf(u32 idx, const Position& pos, int depth);
// Second visit: creates the edges with their priors. False when the
// arena is full (a collection is then scheduled).
bool expand(u32 idx, const Position& pos);
// The edge PUCT picks at node `idx`.
u32 select_edge(u32 idx) const;
bool is_repetition(const Position& pos) const;
// Finds the node for `root` in the previous tree and makes it the root.
// Returns the number of nodes kept, 0 when nothing could be reused.
size_t reuse_tree(const Position& root);
// Empties the tree, leaving an unexpanded root for `root`.
void clear_tree(const Position& root);
#ifdef RIGBY_VERIFY_TREE
// Checks the tree from root_pos_; `history` ends with the root's key.
void verify_tree(const std::vector<u64>& history) const;
#endif
void compute_time_limit(const SearchLimits& limits);
i64 elapsed_ms() const;
bool should_stop(const SearchLimits& limits) const;
bool best_move_settled(i64 ms, i64 limit_ms) const;
// The edge with the most visits at node `idx`, 0 when it has none.
u32 best_edge(u32 idx) const;
// Q of an edge from the view of the side choosing it (0 when unvisited).
float edge_q(const Edge& e) const { return e.visits ? tree_.node(e.child).q : 0.0f; }
void print_info() const;
std::vector<Move> principal_variation() const;
void draw_dashboard(bool done);
};
} // namespace rigby
+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("MCTS chess engine", LABEL); right.add("MCGS 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 "mcts.h" #include "mcgs.h"
#include "perft.h" #include "perft.h"
#include "policy.h" #include "policy.h"
#include "position.h" #include "position.h"