diff --git a/CHANGELOG.md b/CHANGELOG.md index f4797ef..0cbe056 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,15 @@ A rewrite of the engine core and the training pipeline. See - Superko/Tromp-Taylor state was shared with search playouts; simple ko was set on any single-stone capture - Self-play and arena games were truncated at 83 moves and scored unfinished - ONNX export traced BatchNorm in training mode when the wrapper module was not in `eval()` +- Every evaluation match of a training run replayed the same random openings, because the arena + seed was the length of the match name; each match now draws its own +- A run stopped between saving the first checkpoint and exporting it could not be resumed +- The training loop failed after the first generation when an anchor such as GNU Go was not + installed; it now checks its anchors before starting and says what to install +- Arena and self-play result files are written through a rename, so a resumed run never reads + a partial one +- `--set` on an existing run was ignored without a word; a value that would change the run's + settings is now refused ### Changed @@ -43,6 +52,10 @@ A rewrite of the engine core and the training pipeline. See per-generation cosine schedule, resumable `python -m training.loop` - Evaluation: arena with paired openings, GNU Go (or any GTP engine) as anchors with dead-stone adjudication, Wilson intervals, Elo, SPRT, and a Bradley-Terry ladder across generations +- ONNX export uses PyTorch's `torch.export`-based exporter (opset 18) in place of the deprecated + TorchScript one, and is verified at several batch sizes; `training/requirements.txt` asks for + PyTorch 2.9 or newer +- `scripts/setup.sh` installs GNU Go on Fedora (`dnf`) as well as Debian and Ubuntu ### Web diff --git a/cmd/gofer/commands.go b/cmd/gofer/commands.go index d5b452e..9dd39c7 100644 --- a/cmd/gofer/commands.go +++ b/cmd/gofer/commands.go @@ -186,11 +186,22 @@ func cmdSelfplay(args []string) error { st.Resigned, st.FalseResigns, st.NoResignWithTrigger) if *statsPath != "" { data, _ := json.MarshalIndent(out, "", " ") - return os.WriteFile(*statsPath, data, 0o644) + return writeFileAtomic(*statsPath, data) } return nil } +// writeFileAtomic writes data to path through a temporary file and a rename. +// The training loop treats these result files as proof that a match or a +// self-play phase finished, so it must never find a partial one. +func writeFileAtomic(path string, data []byte) error { + tmp := path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + return os.Rename(tmp, path) +} + func cmdArena(args []string) error { fs := flag.NewFlagSet("arena", flag.ExitOnError) var nf netFlags @@ -245,7 +256,7 @@ func cmdArena(args []string) error { res.Elo, res.EloLow, res.EloHigh, 100*res.BlackWinRate, res.SPRTDecision) if *jsonPath != "" { data, _ := json.MarshalIndent(res, "", " ") - return os.WriteFile(*jsonPath, data, 0o644) + return writeFileAtomic(*jsonPath, data) } return nil } diff --git a/docs/training.md b/docs/training.md index ee8ec44..bcf4fe2 100644 --- a/docs/training.md +++ b/docs/training.md @@ -8,6 +8,12 @@ scripts/setup.sh gpu # NVIDIA machine: GPU ONNX Runtime and CUDA PyTorch make test ``` +The default anchors are GNU Go, which `scripts/setup.sh` installs with +`apt-get` or `dnf`. The loop checks that every anchor can play before it +starts, so a missing GNU Go is reported at once rather than after the first +generation. To train without it, create the run with other anchors, e.g. +`--set 'anchors=["rollout,visits=800"]'`. + ## Run ```bash @@ -43,10 +49,15 @@ Each generation: `sample_reuse` samples per new row, with a random board symmetry per sample. The loss on the new data *before* training (logged as "previous net on new data") is an honest held-out metric. -3. **Export** the network to ONNX and verify it against PyTorch. +3. **Export** the network to ONNX and verify it against PyTorch at batch + 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). All results feed a - Bradley-Terry fit in `eval/ratings.json` with `gen-0000` at 0 Elo. + generations against fixed anchors (GNU Go by default). Each match plays + its own set of random openings, each opening once with either color. 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 + accumulates along the chain of generations. 5. **Champion** (anchor generations only): if the new network is rated above the champion, it plays the champion directly (up to `champion_games` games at `champion_visits`) and becomes the new champion only if the match's SPRT @@ -63,8 +74,9 @@ Each generation: undecided promotes nothing. `go test ./internal/arena` checks these rates by simulating thousands of matches with color and opening advantages. -There is no gating for training: like AlphaZero and KataGo, the newest -network always plays the next self-play. The champion is only the best +There is no gating for training: as in AlphaZero, the newest network always +plays the next self-play. (KataGo does gate, lightly: a candidate must win +100 of 200 games against the current network.) The champion is only the best network so far, the one worth downloading. ## Champions and releases @@ -95,7 +107,11 @@ the examples) is not touched; update it deliberately when a release is worth promoting. Override settings when creating a run, e.g. -`--set games_per_gen=1000 --set full_visits=400 --set train.lr=1e-3`. +`--set games_per_gen=1000 --set full_visits=400 --set train.lr=1e-3`. They are +saved in the run's `config.json`. Resuming with the same `--set` values (or +none) is fine; values that would change an existing run are refused, so a +setting is never ignored silently. To change a run that has started, edit its +`config.json`. ## Throughput diff --git a/internal/nn/features.go b/internal/nn/features.go index 1891479..ab3344d 100644 --- a/internal/nn/features.go +++ b/internal/nn/features.go @@ -4,7 +4,7 @@ package nn import "github.com/DevomB/gofer/internal/game" -// Feature layout (schema 3). Keep in sync with training/gofer/features.py. +// Feature layout (schema 3). Keep in sync with training/features.py. const ( SchemaVersion = 3 diff --git a/scripts/setup.sh b/scripts/setup.sh index 926ca7f..6be3068 100755 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# One-shot setup for a fresh Ubuntu/Debian machine (laptop, Vultr, Lambda, ...): +# One-shot setup for a fresh Linux machine (laptop, Vultr, Lambda, ...): # Go toolchain check, GNU Go (evaluation anchor), ONNX Runtime, Python venv, build. +# GNU Go is installed with apt-get (Debian/Ubuntu) or dnf (Fedora). # # scripts/setup.sh # CPU box # scripts/setup.sh gpu # NVIDIA box: GPU ONNX Runtime + CUDA PyTorch @@ -11,8 +12,14 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)" cd "$ROOT" command -v go >/dev/null || { echo "install Go 1.22+ first: https://go.dev/dl/" >&2; exit 1; } -if command -v apt-get >/dev/null && ! command -v gnugo >/dev/null && [[ ! -x /usr/games/gnugo ]]; then - sudo apt-get install -y gnugo python3-venv || echo "warning: could not install gnugo (evaluation anchors will be unavailable)" +if ! command -v gnugo >/dev/null && [[ ! -x /usr/games/gnugo ]]; then + if command -v apt-get >/dev/null; then + sudo apt-get install -y gnugo python3-venv || echo "warning: could not install gnugo (the default evaluation anchors need it)" + elif command -v dnf >/dev/null; then + sudo dnf install -y gnugo || echo "warning: could not install gnugo (the default evaluation anchors need it)" + else + echo "warning: install GNU Go yourself (the default evaluation anchors need it)" + fi fi scripts/install-ort.sh "$FLAVOR" diff --git a/training/elo.py b/training/elo.py index 6459111..0261854 100644 --- a/training/elo.py +++ b/training/elo.py @@ -12,6 +12,11 @@ def fit(results: list[dict], anchor: str, prior_games: float = 1.0, iters: int = Draws count as half a win each way. `prior_games` adds that many virtual drawn games between every pair that met, which keeps perfect scores finite. Returns {player: {"elo": r, "stderr": s, "games": n}} with `anchor` at 0. + + stderr treats the other players' ratings as exact: it is the uncertainty of + a player's rating against the opponents it actually played, not against the + anchor. Along a chain of generations the error against the anchor is + larger, because it accumulates over every link of the chain. """ wins: dict[tuple[str, str], float] = defaultdict(float) games: dict[tuple[str, str], float] = defaultdict(float) @@ -42,7 +47,7 @@ def fit(results: list[dict], anchor: str, prior_games: float = 1.0, iters: int = ref = gamma.get(anchor, 1.0) out = {} for p in players: - # Fisher information of log-strength gives an approximate standard error. + # Fisher information of this player's log-strength alone (see the docstring). info = sum(games[(p, q)] * gamma[p] * gamma[q] / (gamma[p] + gamma[q]) ** 2 for q in players if (p, q) in games) se = 400 / math.log(10) / math.sqrt(info) if info > 0 else float("inf") n = sum(games[(p, q)] for q in players if (p, q) in games) - prior_games * sum(1 for q in players if (p, q) in games) diff --git a/training/export.py b/training/export.py index cf4a77d..7a040d7 100644 --- a/training/export.py +++ b/training/export.py @@ -3,6 +3,8 @@ from __future__ import annotations import argparse +import contextlib +import logging from pathlib import Path import numpy as np @@ -11,6 +13,8 @@ from training.features import NUM_GLOBALS, NUM_PLANES from training.model import GoferNet +OPSET = 18 + class _Inference(torch.nn.Module): def __init__(self, net: GoferNet) -> None: @@ -22,24 +26,40 @@ def forward(self, spatial: torch.Tensor, glob: torch.Tensor): return policy, value +@contextlib.contextmanager +def _quiet_exporter(): + """The exporter warns about every torchvision operator it cannot register + when torchvision is not installed; the network uses none of them.""" + log = logging.getLogger("torch.onnx._internal.exporter._registration") + level = log.level + log.setLevel(logging.ERROR) + try: + yield + finally: + log.setLevel(level) + + def export(model: GoferNet, path: Path, verify: bool = True) -> None: model = model.cpu().eval() s = model.cfg.board_size spatial = torch.zeros(2, NUM_PLANES, s, s) glob = torch.zeros(2, NUM_GLOBALS) tmp = path.with_suffix(".tmp.onnx") - # The wrapper must be in eval mode too: export traces (and afterwards - # restores) the mode of the module it is given, BatchNorm included. - torch.onnx.export( - _Inference(model).eval(), - (spatial, glob), - tmp, - input_names=["spatial", "global"], - output_names=["policy", "value"], - dynamic_axes={"spatial": {0: "batch"}, "global": {0: "batch"}, "policy": {0: "batch"}, "value": {0: "batch"}}, - opset_version=17, - dynamo=False, - ) + batch = {0: torch.export.Dim.DYNAMIC} + # The wrapper must be in eval mode too: the exporter traces the module it + # is given in the mode it is in, BatchNorm included. + with _quiet_exporter(): + program = torch.onnx.export( + _Inference(model).eval(), + (spatial, glob), + input_names=["spatial", "global"], + output_names=["policy", "value"], + dynamic_shapes=(batch, batch), + opset_version=OPSET, + dynamo=True, + verbose=False, + ) + program.save(tmp) model.eval() if verify: verify_onnx(model, tmp) @@ -47,18 +67,24 @@ def export(model: GoferNet, path: Path, verify: bool = True) -> None: def verify_onnx(model: GoferNet, path: Path, atol: float = 1e-3) -> None: + """Compare the exported graph with PyTorch on random positions. The batch + sizes differ from the one the graph was traced with (2) and include 1, so + a graph whose batch dimension came out fixed fails here, not in self-play.""" import onnxruntime as ort s = model.cfg.board_size rng = np.random.default_rng(0) - spatial = (rng.random((5, NUM_PLANES, s, s)) < 0.3).astype(np.float32) - glob = rng.standard_normal((5, NUM_GLOBALS)).astype(np.float32) sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"]) - p_onnx, v_onnx = sess.run(None, {"spatial": spatial, "global": glob}) - with torch.no_grad(): - p_t, v_t, _ = model(torch.from_numpy(spatial), torch.from_numpy(glob)) - if not (np.allclose(p_onnx, p_t.numpy(), atol=atol) and np.allclose(v_onnx, v_t.numpy(), atol=atol)): - raise RuntimeError(f"ONNX export of {path} does not match PyTorch") + for batch in (1, 5): + spatial = (rng.random((batch, NUM_PLANES, s, s)) < 0.3).astype(np.float32) + glob = rng.standard_normal((batch, NUM_GLOBALS)).astype(np.float32) + p_onnx, v_onnx = sess.run(None, {"spatial": spatial, "global": glob}) + with torch.no_grad(): + p_t, v_t, _ = model(torch.from_numpy(spatial), torch.from_numpy(glob)) + if p_onnx.shape != tuple(p_t.shape) or v_onnx.shape != tuple(v_t.shape): + raise RuntimeError(f"ONNX export of {path} has output shapes {p_onnx.shape}, {v_onnx.shape} for a batch of {batch}") + if not (np.allclose(p_onnx, p_t.numpy(), atol=atol) and np.allclose(v_onnx, v_t.numpy(), atol=atol)): + raise RuntimeError(f"ONNX export of {path} does not match PyTorch") def main() -> None: diff --git a/training/loop.py b/training/loop.py index 9467e58..bd7ad12 100644 --- a/training/loop.py +++ b/training/loop.py @@ -21,6 +21,7 @@ import subprocess import sys import time +import zlib from dataclasses import dataclass, field from pathlib import Path @@ -86,8 +87,7 @@ def __init__(self, root: Path, cfg: LoopConfig, gofer: Path, threads: int, relea self.env = dict(os.environ) if "ONNXRUNTIME_SHARED_LIBRARY_PATH" not in self.env: self.env["ONNXRUNTIME_SHARED_LIBRARY_PATH"] = find_ort_library() - if Path("/usr/games").is_dir(): # Debian/Ubuntu install gnugo there - self.env["PATH"] = self.env.get("PATH", "") + ":/usr/games" + self.env["PATH"] = tool_path() # ---- bookkeeping ------------------------------------------------- def log(self, msg: str) -> None: @@ -125,15 +125,18 @@ def gofer_run(self, args: list[str]) -> None: # ---- phases ------------------------------------------------------ def init(self) -> None: - if self.ckpt_path(0).exists(): - return - torch.manual_seed(0) - mc = ModelConfig(board_size=self.cfg.board_size, blocks=self.cfg.blocks, channels=self.cfg.channels) - model = GoferNet(mc).to(device()) - opt = make_optimizer(model, self.cfg.train) - save_checkpoint(self.ckpt_path(0), model, opt, 0) - export(model, self.model_path(0)) - self.log(f"initialized {mc.blocks}x{mc.channels} network ({param_count(model):,} parameters)") + """Create the random initial network. The checkpoint and its ONNX export + are checked separately, so a run stopped between the two still starts.""" + c = self.cfg + if not self.ckpt_path(0).exists(): + torch.manual_seed(0) + mc = ModelConfig(board_size=c.board_size, blocks=c.blocks, channels=c.channels) + model = GoferNet(mc).to(device()) + save_checkpoint(self.ckpt_path(0), model, make_optimizer(model, c.train), 0) + self.log(f"initialized {mc.blocks}x{mc.channels} network ({param_count(model):,} parameters)") + if not self.model_path(0).exists(): + model, _, _ = load_checkpoint(self.ckpt_path(0), c.train, device()) + export(model, self.model_path(0)) def selfplay(self, gen: int) -> None: if self.is_done(gen, "selfplay"): @@ -188,7 +191,7 @@ def match(self, a: str, b: str, games: int, visits: int, tag: str, extra: list[s if not out.exists(): self.gofer_run([ "arena", "-a", a, "-b", b, "-games", str(games), "-visits", str(visits), "-size", str(self.cfg.board_size), - "-komi", str(self.cfg.komi), "-parallel", str(2 * self.threads), "-json", str(out), "-seed", str(len(tag)), + "-komi", str(self.cfg.komi), "-parallel", str(2 * self.threads), "-json", str(out), "-seed", str(match_seed(tag)), *(extra or []), ]) return json.loads(out.read_text()) @@ -298,6 +301,74 @@ def anchor_label(spec: str) -> str: return re.sub(r"[^A-Za-z0-9.-]+", "-", label) +def match_seed(tag: str) -> int: + """Arena seed for the match named tag. Each match gets its own seed, so each + draws its own random openings; the same match always gets the same seed.""" + return zlib.crc32(tag.encode()) + + +def tool_path() -> str: + """PATH for the engine and the programs it starts; Debian and Ubuntu install gnugo in /usr/games.""" + path = os.environ.get("PATH", "") + return f"{path}:/usr/games" if Path("/usr/games").is_dir() else path + + +def anchor_problems(anchors: list[str], path: str) -> list[str]: + """Anchors that cannot play on this machine, one message each: an external + program that is not on path, or a network file that is missing. Specs are + those of `gofer arena` (see cmd/gofer/engine.go).""" + problems = [] + for spec in anchors: + head, *opts = spec.split(",") + kind, _, arg = head.partition(":") + if kind == "gnugo": + program = next((o.split("=", 1)[1] for o in opts if o.startswith("bin=")), "gnugo") + if shutil.which(program, path=path) is None: + problems.append(f"{spec}: GNU Go ({program}) is not installed") + elif kind == "gtp": + program = (spec.removeprefix("gtp:").split() or [""])[0] + if shutil.which(program, path=path) is None: + problems.append(f"{spec}: program {program!r} not found") + elif kind == "nn" and not Path(arg).exists(): + problems.append(f"{spec}: network file {arg} not found") + return problems + + +def check_anchors(anchors: list[str], run: Path) -> None: + """Stop before any work is done if an anchor cannot play: the first anchor + match comes only after a full generation of self-play and training.""" + problems = anchor_problems(anchors, tool_path()) + if not problems: + return + lines = ["cannot start: these anchors cannot play on this machine", *(f" {p}" for p in problems)] + if any("GNU Go" in p for p in problems): + lines.append("Install GNU Go: sudo dnf install gnugo (Fedora), sudo apt-get install gnugo (Debian, Ubuntu).") + lines.append(f"""To use other anchors: --set 'anchors=["rollout,visits=800"]' on a new run, or edit "anchors" in {run / 'config.json'}.""") + raise SystemExit("\n".join(lines)) + + +def apply_overrides(d: dict, overrides: list[str]) -> list[str]: + """Apply KEY=VALUE settings to a LoopConfig dict in place. Returns the keys + whose value changed.""" + changed = [] + for kv in overrides: + k, eq, v = kv.partition("=") + if not eq: + raise SystemExit(f"--set expects KEY=VALUE, got {kv!r}") + target = d["train"] if k.startswith("train.") else d + name = k.removeprefix("train.") + if name not in target: + raise SystemExit(f"unknown config key {k}") + try: + new = v if isinstance(target[name], str) else json.loads(v) + except json.JSONDecodeError: + raise SystemExit(f"--set {k}: {v!r} is not a valid value (current: {json.dumps(target[name])})") from None + if new != target[name]: + changed.append(k) + target[name] = new + return changed + + def find_ort_library() -> str: import onnxruntime @@ -320,19 +391,16 @@ def main() -> None: help="publish each new champion as a GitHub Release with gh (default: $GOFER_RELEASE_REPO)") args = ap.parse_args() cfg_path = args.run / "config.json" - if cfg_path.exists(): - cfg = LoopConfig.from_dict(json.loads(cfg_path.read_text())) - else: - d = dataclasses.asdict(LoopConfig()) - for kv in args.set: - k, v = kv.split("=", 1) - target = d["train"] if k.startswith("train.") else d - k = k.removeprefix("train.") - if k not in target: - raise SystemExit(f"unknown config key {k}") - cur = target[k] - target[k] = json.loads(v) if not isinstance(cur, str) else v - cfg = LoopConfig.from_dict(d) + resuming = cfg_path.exists() + d = dataclasses.asdict(LoopConfig.from_dict(json.loads(cfg_path.read_text())) if resuming else LoopConfig()) + changed = apply_overrides(d, args.set) + if resuming and changed: + # the same command resumes a run, so --set may repeat the run's settings, but not change them + raise SystemExit(f"{cfg_path} already fixes this run's settings, and --set would change {', '.join(changed)}. " + "Edit that file to change a running run, or start a new one with another --run directory.") + cfg = LoopConfig.from_dict(d) + check_anchors(cfg.anchors, args.run) + if not resuming: args.run.mkdir(parents=True, exist_ok=True) cfg_path.write_text(json.dumps(dataclasses.asdict(cfg), indent=2)) torch.set_num_threads(args.threads) diff --git a/training/requirements.txt b/training/requirements.txt index cc9ce1f..73db743 100644 --- a/training/requirements.txt +++ b/training/requirements.txt @@ -1,4 +1,4 @@ -torch>=2.2 +torch>=2.9 # training.export uses the torch.export-based ONNX exporter numpy>=1.24 onnx>=1.15 onnxruntime>=1.17 diff --git a/training/tests/test_loop.py b/training/tests/test_loop.py new file mode 100644 index 0000000..4b23ed7 --- /dev/null +++ b/training/tests/test_loop.py @@ -0,0 +1,125 @@ +"""Tests for the training loop's bookkeeping (no gofer binary needed).""" + +from __future__ import annotations + +import json +import stat +import sys +from pathlib import Path + +import numpy as np +import pytest + +from training.features import NUM_GLOBALS, NUM_PLANES +from training import loop +from training.loop import LoopConfig, Run, anchor_problems, match_seed + + +@pytest.fixture +def run(tmp_path, monkeypatch): + r = Run(tmp_path / "run", LoopConfig(blocks=1, channels=8, anchors=[]), Path("gofer"), threads=1) + monkeypatch.setattr(r, "log", lambda msg: None) + return r + + +def executable(path: Path) -> Path: + path.write_text("#!/bin/sh\n") + path.chmod(path.stat().st_mode | stat.S_IEXEC) + return path + + +def test_every_match_gets_its_own_openings(run, monkeypatch): + # These tags have the same length. The seed used to be len(tag), so every + # evaluation of a run replayed the same openings. + tags = ["gen-0001-vs-gen-0000", "gen-0002-vs-gen-0001", "gen-0002-vs-gnugo-l1", "gen-0002-vs-gnugo-l6"] + assert len({len(t) for t in tags}) == 1 + assert len({match_seed(t) for t in tags}) == len(tags) + assert match_seed(tags[0]) == match_seed(tags[0]) # a resumed run replays the same match + + calls = [] + + def fake_gofer(args): + calls.append(args) + Path(args[args.index("-json") + 1]).write_text(json.dumps({"wins": 1, "losses": 1, "draws": 0})) + + monkeypatch.setattr(run, "gofer_run", fake_gofer) + for tag in tags[:2]: + run.match("nn:a.onnx", "nn:b.onnx", 2, 8, tag) + seeds = [args[args.index("-seed") + 1] for args in calls] + assert seeds == [str(match_seed(t)) for t in tags[:2]] + run.match("nn:a.onnx", "nn:b.onnx", 2, 8, tags[0]) + assert len(calls) == 2 # a finished match is read back, not replayed + + +def test_init_exports_the_network_when_only_the_checkpoint_exists(run): + import onnxruntime as ort + + run.init() + ckpt, model = run.ckpt_path(0), run.model_path(0) + assert ckpt.exists() and model.exists() + # a run stopped between saving the checkpoint and exporting it + model.unlink() + before = ckpt.read_bytes() + run.init() + assert ckpt.read_bytes() == before + # the engine's contract: these names, any batch size + sess = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"]) + assert [i.name for i in sess.get_inputs()] == ["spatial", "global"] + assert [o.name for o in sess.get_outputs()] == ["policy", "value"] + for batch in (1, 7): + policy, value = sess.run(None, {"spatial": np.zeros((batch, NUM_PLANES, 9, 9), np.float32), + "global": np.zeros((batch, NUM_GLOBALS), np.float32)}) + assert policy.shape == (batch, 82) and value.shape == (batch,) + + +def test_anchor_problems_names_what_is_missing(tmp_path): + empty = tmp_path / "empty" + empty.mkdir() + path = str(empty) + assert anchor_problems(["rollout,visits=800", "uniform"], path) == [] + (problem,) = anchor_problems(["gnugo,level=1"], path) + assert "gnugo,level=1" in problem and "GNU Go" in problem + assert len(anchor_problems(["gnugo,level=1", "gnugo,level=6", "rollout"], path)) == 2 + assert len(anchor_problems(["gtp:some-engine --mode gtp"], path)) == 1 + assert len(anchor_problems([f"nn:{tmp_path}/missing.onnx,visits=100"], path)) == 1 + + executable(empty / "gnugo") + executable(empty / "some-engine") + (tmp_path / "net.onnx").write_bytes(b"") + assert anchor_problems(["gnugo,level=1", "gtp:some-engine --mode gtp", f"nn:{tmp_path}/net.onnx,visits=100"], path) == [] + # a GNU Go binary given explicitly + assert anchor_problems([f"gnugo,level=1,bin={empty}/gnugo"], str(tmp_path)) == [] + assert len(anchor_problems([f"gnugo,level=1,bin={empty}/nope"], path)) == 1 + + +def loop_main(monkeypatch, run_dir: Path, *args: str) -> None: + monkeypatch.setattr(sys, "argv", ["training.loop", "--run", str(run_dir), "--gens", "0", *args]) + loop.main() + + +def test_loop_refuses_to_start_when_an_anchor_cannot_play(tmp_path, monkeypatch, capsys): + run_dir = tmp_path / "run" + with pytest.raises(SystemExit) as stop: + loop_main(monkeypatch, run_dir, "--set", 'anchors=["gnugo,level=1,bin=/nonexistent/gnugo", "rollout"]') + message = str(stop.value) + assert "gnugo,level=1" in message and "install gnugo" in message and "rollout:" not in message + # refused before anything was written: a config.json left behind would + # make the next attempt's --set a change to an existing run + assert not run_dir.exists() + + +def test_set_may_repeat_a_runs_settings_but_not_change_them(tmp_path, monkeypatch, capsys): + run_dir = tmp_path / "run" + tiny = ["--set", "blocks=1", "--set", "channels=8", "--set", "anchors=[]"] + loop_main(monkeypatch, run_dir, *tiny) + saved = (run_dir / "config.json").read_text() + assert json.loads(saved)["channels"] == 8 + loop_main(monkeypatch, run_dir, *tiny) # the same command resumes + loop_main(monkeypatch, run_dir) # and so does the command without the settings + with pytest.raises(SystemExit, match="channels"): + loop_main(monkeypatch, run_dir, "--set", "channels=16") + assert (run_dir / "config.json").read_text() == saved + with pytest.raises(SystemExit, match="unknown config key"): + loop_main(monkeypatch, tmp_path / "other", "--set", "chanels=16") + with pytest.raises(SystemExit, match="KEY=VALUE"): + loop_main(monkeypatch, tmp_path / "other", "--set", "channels")