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

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

The bench is unchanged: it never reuses a graph.

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

Bench: 764208

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:36:03 +01:00
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
3 changed files with 925 additions and 256 deletions

No files matched your search

+307
View File
@@ -7,6 +7,8 @@ only from results the owner provides.
| --- | --- | --- | --- | --- | --- |
| 1 | `mcgs-stats` | `bec9871` | 663779 (normal and `STATS=1` builds) | none (never merged) | measurement only; the branch stays on its own |
| 2 | `mcgs-step2-split` | `fb1b8a5` | 663779 (identical to main) | | |
| 3 | `mcgs-step3-core` | `14f672a` | 764208 | [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` | |
## Step 1 measurements
@@ -381,3 +383,308 @@ step 2 were run interleaved.
`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
> 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/, outcome to be filled in.
+513 -222
View File
File diff suppressed because it is too large. Load diff
+105 -34
View File
@@ -19,13 +19,28 @@ enum NodeState : u8 {
TERMINAL_DRAW,
};
// 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 child node is
// created the first time search selects 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 = 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)
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
@@ -33,27 +48,27 @@ struct Edge {
};
static_assert(sizeof(Edge) == 16);
// A position, created when search first reaches it.
// 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;
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;
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.
u8 state = UNEXPANDED;
u16 check = 0;
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.
// 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
@@ -66,16 +81,24 @@ public:
// 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);
// 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.
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 tree
// 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);
@@ -92,23 +115,42 @@ public:
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_ = 1;
u32 root_ = 0;
// 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.
// 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 for MCTS (after Vine, aronpetkovski.com/blog/butterfly-history-mcts):
@@ -208,8 +250,8 @@ public:
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).
// A 32nd of the memory goes to the value hash, the rest to the graph
// (its arenas, split by Tree::EDGES_PER_NODE, and its table).
const size_t bytes = mb * 1024 * 1024;
value_hash_.resize(bytes / 32 / ValueHash::ENTRY_BYTES);
tree_.resize_bytes(bytes - bytes / 32);
@@ -244,10 +286,14 @@ private:
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]).
// 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;
@@ -276,22 +322,40 @@ private:
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);
// 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`.
u32 select_edge(u32 idx) const;
// 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 tree and makes it the root.
// Returns the number of nodes kept, 0 when nothing could be reused.
// 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);
// Empties the tree, leaving an unexpanded root for `root`.
// True when the root node's edges are exactly the legal moves of `root`.
bool root_edges_valid(const Position& root) const;
// After reuse the game history is common to every path, so whether a
// root move is a draw by repetition or the 50-move rule is exact. Makes
// each root edge all draws or no draws accordingly (plan 3.6.7). Returns
// the number of edges changed.
int reconcile_root_edges(const Position& root);
// Whether `child`, reached from the root, is a draw of the game history
// `keys` (which ends with the child's key).
static bool root_child_drawn(const Position& child, const std::vector<u64>& keys);
// Empties the graph, leaving an evaluated, unexpanded root for `root`.
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;
// 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);
@@ -301,8 +365,15 @@ private:
// 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; }
// 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);