diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cbe056..0f47dd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,11 @@ A rewrite of the engine core and the training pipeline. See ### Fixed +- One unplayable game no longer fails a whole evaluation match, and with it the training loop: + the game is left out of the result and listed under `skipped` (the match still fails when more + than a tenth of its games cannot be played). GNU Go is now started with `--positional-superko`, + the ko rule the arena plays; under its default simple ko it could repeat a position, a move the + arena rejects as illegal - Search backed values up with the wrong sign, so it chose the opponent's best move - Fresh searches did no work: the root lost its `Expanded` flag when the node arena reallocated - Transposition table returned other positions' values (no key check; pass collided with the parent) diff --git a/cmd/gofer/engine.go b/cmd/gofer/engine.go index 26f11e7..030b4da 100644 --- a/cmd/gofer/engine.go +++ b/cmd/gofer/engine.go @@ -221,7 +221,10 @@ func (ps playerSpec) factory(pool *nets, sf *searchFlags, seed *int64) func() (a return &arena.MCTSPlayer{Label: ps.label(), Eval: nn.Uniform{}, Config: cfg, Visits: ps.visits}, nil case "gnugo": bin := ps.optOr("bin", "gnugo") - return arena.NewGTPPlayer(ps.label(), []string{bin, "--mode", "gtp", "--level", ps.optOr("level", "10"), "--chinese-rules"}), nil + // The arena plays positional superko. GNU Go's default is simple ko, + // under which it can repeat a position: a move the arena rejects. + return arena.NewGTPPlayer(ps.label(), []string{bin, "--mode", "gtp", "--level", ps.optOr("level", "10"), + "--chinese-rules", "--positional-superko"}), nil default: return arena.NewGTPPlayer(ps.label(), strings.Fields(ps.arg)), nil } diff --git a/docs/training.md b/docs/training.md index bcf4fe2..ecf141d 100644 --- a/docs/training.md +++ b/docs/training.md @@ -53,7 +53,12 @@ Each generation: sizes other than the one it was exported with. 4. **Evaluate**: new vs previous generation, and every `anchor_every` generations against fixed anchors (GNU Go by default). Each match plays - its own set of random openings, each opening once with either color. All + its own set of random openings, each opening once with either color. + GNU Go is started with positional superko, the ko rule of the match. A + game an external program cannot finish (it crashed, or played a move the + match's rules forbid) is replayed up to three times and then left out of + the result and logged; the match fails only if more than a tenth of its + games do. All results feed a Bradley-Terry fit in `eval/ratings.json` with `gen-0000` at 0 Elo. The `±` beside a rating is its error against the opponents that network actually played; against `gen-0000` the error is larger, because it diff --git a/internal/arena/arena_test.go b/internal/arena/arena_test.go index 5b1d234..14d0dbb 100644 --- a/internal/arena/arena_test.go +++ b/internal/arena/arena_test.go @@ -1,11 +1,15 @@ package arena import ( + "fmt" "math" "math/rand" "os" + "reflect" + "strings" "testing" + "github.com/DevomB/gofer/internal/game" "github.com/DevomB/gofer/internal/mcts" "github.com/DevomB/gofer/internal/nn" ) @@ -165,6 +169,78 @@ func TestSPRTErrorRates(t *testing.T) { } } +func TestSPRTPassesOverSkippedGames(t *testing.T) { + s := &SPRT{Elo0: 0, Elo1: 50, Alpha: 0.05, Beta: 0.05} + full := pairs(repeat("AA", 60)...) + s.test(full) + if full.SPRTDecision != "H1" { + t.Fatalf("60 sweeps should accept H1, got %q", full.SPRTDecision) + } + // The same match, except that the first game could not be played. Its + // pair carries no evidence; the test must go on to the pairs after it + // instead of waiting for a game that will never arrive. + r := pairs(repeat("AA", 61)...) + r.Games = r.Games[1:] + r.Skipped = []int{0} + s.test(r) + if r.SPRTDecision != "H1" || r.SPRTPairs != full.SPRTPairs || r.SweepsA != full.SweepsA { + t.Fatalf("skipped game: decision %q after %d pairs (%d sweeps), want H1 after %d (%d)", + r.SPRTDecision, r.SPRTPairs, r.SweepsA, full.SPRTPairs, full.SweepsA) + } +} + +// illegalMover plays on an occupied point: a move the arena's rules reject, +// as an external engine that plays by other rules can. +type illegalMover struct{ MCTSPlayer } + +func (p *illegalMover) GenMove(b *game.Board) (game.Point, bool, error) { + for q := 0; q < b.NumPoints(); q++ { + if b.At(game.Point(q)) != game.Empty { + return game.Point(q), false, nil + } + } + return p.MCTSPlayer.GenMove(b) +} + +func TestUnplayableGameIsLeftOutOfTheResult(t *testing.T) { + uniform := func(label string) MCTSPlayer { + return MCTSPlayer{Label: label, Eval: nn.Uniform{}, Config: mcts.DefaultConfig(), Visits: 4} + } + a := func() (Player, error) { p := uniform("a"); return &p, nil } + var logged []string + cfg := Config{Size: 5, Komi: 0.5, Games: 10, Parallel: 1, OpeningMoves: 1, Seed: 3, + Log: func(f string, args ...any) { logged = append(logged, fmt.Sprintf(f, args...)) }} + + // One game at a time, so the first three players made for B are the + // three attempts at game 0. + made := 0 + b := func() (Player, error) { + made++ + if made <= 3 { + return &illegalMover{uniform("b")}, nil + } + p := uniform("b") + return &p, nil + } + res, err := Run(cfg, a, b) + if err != nil { + t.Fatalf("one unplayable game failed the match: %v", err) + } + if len(res.Games) != 9 || !reflect.DeepEqual(res.Skipped, []int{0}) || res.Wins+res.Losses+res.Draws != 9 { + t.Fatalf("want 9 games counted and game 0 skipped, got %d games, skipped %v, %d-%d-%d", + len(res.Games), res.Skipped, res.Wins, res.Losses, res.Draws) + } + if text := strings.Join(logged, "\n"); !strings.Contains(text, "game 0 left out") || !strings.Contains(text, "illegal move") { + t.Fatalf("the log does not say which game was left out and why:\n%s", text) + } + + // An engine that cannot play at all still fails the match. + broken := func() (Player, error) { return &illegalMover{uniform("b")}, nil } + if _, err := Run(cfg, a, broken); err == nil || !strings.Contains(err.Error(), "could not be played") { + t.Fatalf("a match in which no game can be played returned %v", err) + } +} + func TestWilson(t *testing.T) { lo, hi := wilson(0.5, 100, 1.96) if math.Abs(lo-0.404) > 0.002 || math.Abs(hi-0.596) > 0.002 { @@ -178,7 +254,7 @@ func TestGNUGo(t *testing.T) { } cfg := Config{Size: 9, Komi: 7.5, Games: 2, Parallel: 2, Seed: 1} gnugo := func() (Player, error) { - return NewGTPPlayer("gnugo-l1", []string{"/usr/games/gnugo", "--mode", "gtp", "--level", "1"}), nil + return NewGTPPlayer("gnugo-l1", []string{"/usr/games/gnugo", "--mode", "gtp", "--level", "1", "--chinese-rules", "--positional-superko"}), nil } weak := func() (Player, error) { return &MCTSPlayer{Label: "uniform-1", Eval: nn.Uniform{}, Config: mcts.DefaultConfig(), Visits: 1}, nil diff --git a/internal/arena/match.go b/internal/arena/match.go index ee4d7e7..f9af545 100644 --- a/internal/arena/match.go +++ b/internal/arena/match.go @@ -6,6 +6,7 @@ import ( "math/rand" "os" "path/filepath" + "sort" "sync" "time" @@ -85,10 +86,20 @@ type Result struct { SPRTPairs int `json:"sprt_pairs,omitempty"` // complete opening pairs the test used, in order SweepsA int `json:"sprt_sweeps_a,omitempty"` // pairs A won twice SweepsB int `json:"sprt_sweeps_b,omitempty"` // pairs B won twice + Skipped []int `json:"skipped,omitempty"` // indexes of games that could not be played (see Run) ElapsedSecond float64 `json:"elapsed_seconds"` } +// maxSkipped is how many games of a match may fail before the match does: a +// tenth of it, and at least one. +func maxSkipped(games int) int { return max(1, games/10) } + // Run plays the match. newA/newB build a fresh player for each game. +// +// A game that fails three times (an external engine crashed, or played a move +// that is illegal under the match's rules) is left out of the result and +// listed in Skipped; the match itself fails only when more than a tenth of +// its games do, which points at a broken engine rather than a bad game. func Run(cfg Config, newA, newB func() (Player, error)) (*Result, error) { if cfg.Games%2 == 1 { cfg.Games++ @@ -135,7 +146,7 @@ func Run(cfg Config, newA, newB func() (Player, error)) (*Result, error) { // External engines occasionally crash (GNU Go 3.8 has known // assertion failures); replay the game with fresh players - // before giving up on the match. + // before giving up on it. var ( out Game nameA, nameB string @@ -149,9 +160,15 @@ func Run(cfg Config, newA, newB func() (Player, error)) (*Result, error) { } mu.Lock() if err != nil { - errOut = err + res.Skipped = append(res.Skipped, g) + if len(res.Skipped) > maxSkipped(cfg.Games) { + errOut = fmt.Errorf("arena: %d of %d games could not be played, the last one: %w", len(res.Skipped), cfg.Games, err) + mu.Unlock() + return + } + cfg.Log("arena: game %d left out of the result: %v", g, err) mu.Unlock() - return + continue } res.NameA, res.NameB = nameA, nameB res.Games = append(res.Games, out) @@ -173,6 +190,7 @@ func Run(cfg Config, newA, newB func() (Player, error)) (*Result, error) { }() } wg.Wait() + sort.Ints(res.Skipped) res.ElapsedSecond = time.Since(start).Seconds() return res, errOut } @@ -333,6 +351,9 @@ func (r *Result) summarize() { } } n := float64(len(r.Games)) + if n == 0 { + return + } r.Score = (float64(r.Wins) + 0.5*float64(r.Draws)) / n r.ScoreLow, r.ScoreHigh = wilson(r.Score, n, 1.96) r.Elo, r.EloLow, r.EloHigh = elo(r.Score), elo(r.ScoreLow), elo(r.ScoreHigh) @@ -363,16 +384,25 @@ func sweepProb(d float64) float64 { return 1 / (1 + math.Pow(10, -2*d/400)) } // test runs the SPRT over the complete opening pairs at the start of the // match (pairs 0, 1, 2, ... while both games of each are in), stopping at the // first pair whose evidence crosses a bound, and records the outcome in r. +// A pair with a skipped game is passed over: like a split pair, it says +// nothing about who is stronger. func (t *SPRT) test(r *Result) { byIndex := make(map[int]Game, len(r.Games)) for _, g := range r.Games { byIndex[g.Index] = g } + skipped := make(map[int]bool, len(r.Skipped)) + for _, i := range r.Skipped { + skipped[i] = true + } q0, q1 := sweepProb(t.Elo0), sweepProb(t.Elo1) winA, winB := math.Log(q1/q0), math.Log((1-q1)/(1-q0)) lower, upper := math.Log(t.Beta/(1-t.Alpha)), math.Log((1-t.Beta)/t.Alpha) r.LLR, r.SPRTPairs, r.SweepsA, r.SweepsB = 0, 0, 0, 0 for k := 0; ; k++ { + if skipped[2*k] || skipped[2*k+1] { + continue + } g0, ok0 := byIndex[2*k] g1, ok1 := byIndex[2*k+1] if !ok0 || !ok1 { diff --git a/training/loop.py b/training/loop.py index bd7ad12..8c01cb3 100644 --- a/training/loop.py +++ b/training/loop.py @@ -194,6 +194,9 @@ def match(self, a: str, b: str, games: int, visits: int, tag: str, extra: list[s "-komi", str(self.cfg.komi), "-parallel", str(2 * self.threads), "-json", str(out), "-seed", str(match_seed(tag)), *(extra or []), ]) + skipped = json.loads(out.read_text()).get("skipped") + if skipped: + self.log(f"eval: {len(skipped)} of the {games} games of {tag} could not be played and are left out of its result") return json.loads(out.read_text()) def evaluate(self, gen: int) -> None: diff --git a/training/tests/test_loop.py b/training/tests/test_loop.py index 4b23ed7..cd2fdce 100644 --- a/training/tests/test_loop.py +++ b/training/tests/test_loop.py @@ -51,6 +51,18 @@ def fake_gofer(args): assert len(calls) == 2 # a finished match is read back, not replayed +def test_games_the_arena_could_not_play_are_reported(run, monkeypatch): + def fake_gofer(args): + Path(args[args.index("-json") + 1]).write_text(json.dumps({"wins": 30, "losses": 9, "draws": 0, "skipped": [17]})) + + logged = [] + monkeypatch.setattr(run, "gofer_run", fake_gofer) + monkeypatch.setattr(run, "log", logged.append) + r = run.match("nn:a.onnx", "gnugo,level=1", 40, 100, "gen-0004-vs-gnugo-l1") + assert (r["wins"], r["losses"]) == (30, 9) + assert len(logged) == 1 and "1 of the 40 games of gen-0004-vs-gnugo-l1" in logged[0] + + def test_init_exports_the_network_when_only_the_checkpoint_exists(run): import onnxruntime as ort