From 30dc20a15863b6eadd51096c78d3d4ef5d117eb3 Mon Sep 17 00:00:00 2001 From: DevomB <70069338+DevomB@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:03:49 -0800 Subject: [PATCH 1/2] training: start a run from another run's network (init_from) The network's weights do not depend on the board size, so a network trained on 9x9 can start a run on 13x13. init_from names the checkpoint; the new run takes the weights and nothing else (own optimizer state, learning-rate schedule, replay window and rating ladder). - loop refuses a missing checkpoint, or one of another network size, before the run directory is created - champion.json and release notes name the starting checkpoint, because the game counts there cover only the new run - docs: "Moving to a larger board" Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 4 ++ docs/training.md | 31 ++++++++++++++- training/loop.py | 39 ++++++++++++++++--- training/release.py | 3 +- training/tests/test_loop.py | 70 ++++++++++++++++++++++++++++++++++ training/tests/test_release.py | 10 +++++ 6 files changed, 149 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cbe056..51aeb86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ A rewrite of the engine core and the training pipeline. See ### Added +- `init_from`: a training run can start from another run's network instead of random weights, + on any board size, since the network's weights do not depend on it + (`--set board_size=13 --set init_from=runs/9x9/ckpt/gen-0044.pt`). Champions record the + starting checkpoint - Champions and releases: on anchor generations, a network rated above the current champion plays it directly (SPRT); a winner becomes the champion, is kept in `runs//champion/`, and with `--release-repo OWNER/REPO` is published as a GitHub Release whose `gofer-9x9.onnx` diff --git a/docs/training.md b/docs/training.md index bcf4fe2..046bfb9 100644 --- a/docs/training.md +++ b/docs/training.md @@ -30,7 +30,7 @@ runs/9x9/ state.json current generation, completed phases, all match results log.txt human-readable log metrics.jsonl per-generation self-play, training and evaluation metrics - models/ gen-NNNN.onnx (gen-0000 is the random initial network) + models/ gen-NNNN.onnx (gen-0000 is the random initial network, or the one named by init_from) ckpt/ gen-NNNN.pt (model + optimizer state) data/gen-NNNN/ self-play shards (.npz) sgf/gen-NNNN/ every self-play game @@ -79,6 +79,35 @@ 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. +## Moving to a larger board + +No weight of the network depends on the board size (it is convolutions and +board-wide pooling), so a network trained on one size can start a run on +another. `init_from` names the checkpoint to start from: + +```bash +.venv/bin/python -m training.loop --run runs/13x13 --gofer bin/gofer --hours 48 \ + --set board_size=13 --set init_from=runs/9x9/ckpt/gen-0044.pt \ + --set temp_moves=20 --set champion_min_elo=0 +``` + +The new run takes the weights and nothing else: its own optimizer state, its +own learning-rate schedule, its own replay window and its own rating ladder, +on which `gen-0000` (the network it started from) is 0. That is why +`champion_min_elo` is lowered: generation 0 is no longer random play. The +checkpoint must hold a network of the run's `blocks` and `channels`, and is +read once, when the run is created; resuming does not need it. A champion's +`champion.json` and release notes name the starting checkpoint, because the +games counted there are only this run's. + +Settings counted in moves or rows were chosen for 9×9 and want scaling with +the board: `temp_moves`, and the replay window (`window_min`, `window_growth`, +`window_max`), since a 13×13 game yields more rows than a 9×9 game. + +A network trained on only the new size from then on is not trained on the old +one any more; measure it there (`gofer arena -size 9` against the old run's +champion) before calling it a network for both. + ## Champions and releases Every champion is copied to `champion/gen-NNNN/` (network, `champion.json` diff --git a/training/loop.py b/training/loop.py index bd7ad12..c90bef3 100644 --- a/training/loop.py +++ b/training/loop.py @@ -41,6 +41,7 @@ class LoopConfig: komi: float = 7.5 blocks: int = 6 channels: int = 64 + init_from: str = "" # checkpoint (.pt) whose network the run starts from; empty: random weights # self-play games_per_gen: int = 600 full_visits: int = 160 @@ -125,15 +126,20 @@ def gofer_run(self, args: list[str]) -> None: # ---- phases ------------------------------------------------------ def init(self) -> None: - """Create the random initial network. The checkpoint and its ONNX export - are checked separately, so a run stopped between the two still starts.""" + """Create the initial network: random weights, or the network of the + checkpoint named by init_from. 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()) + if c.init_from: + model = load_network(Path(c.init_from), c).to(device()) + origin = f"started from the network of {c.init_from}: {c.blocks}x{c.channels}" + else: + torch.manual_seed(0) + model = GoferNet(ModelConfig(board_size=c.board_size, blocks=c.blocks, channels=c.channels)).to(device()) + origin = f"initialized {c.blocks}x{c.channels} network" 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)") + self.log(f"{origin} ({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)) @@ -261,6 +267,7 @@ def promote(self, gen: int, ratings: dict, match: dict | None) -> None: "match": {k: match.get(k) for k in keep} if match else None, "anchors": [r for r in self.state.get("results", []) if r["a"] == name and not r["b"].startswith("gen-")], "board_size": c.board_size, "komi": c.komi, "blocks": c.blocks, "channels": c.channels, + "init_from": c.init_from, "games": c.games_per_gen * len(selfplay), "positions": sum(s["rows"] for s in selfplay), "sha256": release.sha256(asset), } @@ -301,6 +308,24 @@ def anchor_label(spec: str) -> str: return re.sub(r"[^A-Za-z0-9.-]+", "-", label) +def load_network(path: Path, cfg: LoopConfig) -> GoferNet: + """The network of checkpoint path, for a run with settings cfg. No weight + depends on the board size (the network is convolutions and board-wide + pooling), so a network trained on one size can start a run on another. + The optimizer state is left behind: the new run has its own learning-rate + schedule.""" + if not path.is_file(): + raise SystemExit(f"cannot start: init_from names {path}, which is not a file") + ck = torch.load(path, map_location="cpu", weights_only=False) + mc = ModelConfig(**{**ck["model_config"], "board_size": cfg.board_size}) + if (mc.blocks, mc.channels) != (cfg.blocks, cfg.channels): + raise SystemExit(f"cannot start: {path} holds a {mc.blocks}x{mc.channels} network and this run is set to " + f"{cfg.blocks}x{cfg.channels}. Add --set blocks={mc.blocks} --set channels={mc.channels}.") + model = GoferNet(mc) + model.load_state_dict(ck["model"]) + return model + + 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.""" @@ -400,6 +425,8 @@ def main() -> None: "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 cfg.init_from and not (args.run / "ckpt" / "gen-0000.pt").exists(): + load_network(Path(cfg.init_from), cfg) # refuse a missing or mismatched checkpoint before anything is written if not resuming: args.run.mkdir(parents=True, exist_ok=True) cfg_path.write_text(json.dumps(dataclasses.asdict(cfg), indent=2)) diff --git a/training/release.py b/training/release.py index 9088d96..6008045 100644 --- a/training/release.py +++ b/training/release.py @@ -86,7 +86,8 @@ def notes(info: dict, repo: str) -> str: lines.append(f"| Latest anchor results | {anchors} |") lines += [ f"| Network | {info['blocks']} blocks × {info['channels']} channels, {size}×{size}, komi {info['komi']} |", - f"| Training so far | {info['gen']} generations, {info['games']:,} self-play games, {info['positions']:,} positions |", + f"| Training so far | {info['gen']} generations, {info['games']:,} self-play games, {info['positions']:,} positions" + f"{', on top of the network this run started from (`' + Path(info['init_from']).name + '`)' if info.get('init_from') else ''} |", f"| SHA-256 | `{info['sha256']}` |", "", f"Play it: `bin/gofer play -model {asset}` or `bin/gofer gtp -model {asset}` (GTP, for Sabaki or Lizzie).", diff --git a/training/tests/test_loop.py b/training/tests/test_loop.py index 4b23ed7..ce0fff0 100644 --- a/training/tests/test_loop.py +++ b/training/tests/test_loop.py @@ -123,3 +123,73 @@ def test_set_may_repeat_a_runs_settings_but_not_change_them(tmp_path, monkeypatc loop_main(monkeypatch, tmp_path / "other", "--set", "chanels=16") with pytest.raises(SystemExit, match="KEY=VALUE"): loop_main(monkeypatch, tmp_path / "other", "--set", "channels") + + +def trained_checkpoint(path: Path, size: int = 9) -> Path: + """A checkpoint whose weights differ from the random initial network's.""" + import torch + + from training.model import GoferNet, ModelConfig + from training.train import TrainConfig, make_optimizer, save_checkpoint + + torch.manual_seed(5) + model = GoferNet(ModelConfig(board_size=size, blocks=1, channels=8)) + save_checkpoint(path, model, make_optimizer(model, TrainConfig()), 1234) + return path + + +def test_a_run_can_start_on_a_larger_board_from_another_runs_network(tmp_path, monkeypatch): + import onnxruntime as ort + import torch + + from training.model import GoferNet, ModelConfig + + src = trained_checkpoint(tmp_path / "small-board.pt") + cfg = LoopConfig(board_size=13, blocks=1, channels=8, anchors=[], init_from=str(src)) + r = Run(tmp_path / "run", cfg, Path("gofer"), threads=1) + logged = [] + monkeypatch.setattr(r, "log", logged.append) + r.init() + assert "started from" in logged[0] and "small-board.pt" in logged[0] + + source, start = torch.load(src, weights_only=False), torch.load(r.ckpt_path(0), weights_only=False) + assert start["model_config"]["board_size"] == 13 + assert start["step"] == 0 # the new run has its own schedule + assert source["model"].keys() == start["model"].keys() + assert all(torch.equal(source["model"][k], start["model"][k].cpu()) for k in source["model"]) + + # the exported network plays the new size and is the source network there + model = GoferNet(ModelConfig(board_size=13, blocks=1, channels=8)).eval() + model.load_state_dict(source["model"]) + rng = np.random.default_rng(1) + spatial = (rng.random((3, NUM_PLANES, 13, 13)) < 0.3).astype(np.float32) + glob = rng.standard_normal((3, NUM_GLOBALS)).astype(np.float32) + sess = ort.InferenceSession(str(r.model_path(0)), providers=["CPUExecutionProvider"]) + policy, value = sess.run(None, {"spatial": spatial, "global": glob}) + with torch.no_grad(): + want_policy, want_value, _ = model(torch.from_numpy(spatial), torch.from_numpy(glob)) + assert policy.shape == (3, 13 * 13 + 1) + assert np.allclose(policy, want_policy.numpy(), atol=1e-3) and np.allclose(value, want_value.numpy(), atol=1e-3) + + # a resumed run does not need the source checkpoint any more + src.unlink() + r.init() + + +def test_loop_refuses_a_starting_network_it_cannot_use(tmp_path, monkeypatch, capsys): + src = trained_checkpoint(tmp_path / "small-board.pt") + tiny = ["--set", "anchors=[]", "--set", "board_size=13", "--set", f"init_from={src}"] + run_dir = tmp_path / "run" + with pytest.raises(SystemExit) as stop: + loop_main(monkeypatch, run_dir, *tiny) # the run defaults to 6x64 + assert "1x8" in str(stop.value) and "6x64" in str(stop.value) and "--set blocks=1 --set channels=8" in str(stop.value) + assert not run_dir.exists() + with pytest.raises(SystemExit, match="not a file"): + loop_main(monkeypatch, run_dir, "--set", "anchors=[]", "--set", f"init_from={tmp_path}/missing.pt") + assert not run_dir.exists() + + loop_main(monkeypatch, run_dir, *tiny, "--set", "blocks=1", "--set", "channels=8") + assert json.loads((run_dir / "config.json").read_text())["init_from"] == str(src) + assert (run_dir / "ckpt" / "gen-0000.pt").exists() + src.unlink() + loop_main(monkeypatch, run_dir) # resuming works without the source checkpoint diff --git a/training/tests/test_release.py b/training/tests/test_release.py index 85ffd6a..c7e70bd 100644 --- a/training/tests/test_release.py +++ b/training/tests/test_release.py @@ -142,3 +142,13 @@ def test_no_repo_means_no_publishing(run, tmp_path): run.promote(2, json.loads((run.root / "eval" / "ratings.json").read_text()), None) assert not release.publish_pending(run.root, run.state, "", gh=str(fake_gh(tmp_path))) assert not (tmp_path / "gh.log").exists() + + +def test_notes_say_when_a_run_started_from_another_network(run): + set_ratings(run, {2: 1600.0}) + run.champion(1) + info = json.loads((run.root / "champion" / "gen-0002" / "champion.json").read_text()) + assert info["init_from"] == "" + assert "on top of" not in release.notes(info, "") + text = release.notes({**info, "init_from": "runs/9x9/ckpt/gen-0040.pt"}, "") + assert "on top of the network this run started from (`gen-0040.pt`)" in text From 74c2257e76f947568eb43b8a09788c177fdd53fa Mon Sep 17 00:00:00 2001 From: DevomB <70069338+DevomB@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:15:46 -0800 Subject: [PATCH 2/2] export: --size exports a checkpoint for another board size An ONNX file plays one board size, so measuring a 13x13 run's network on 9x9 needs its checkpoint exported for 9x9. The docs said `gofer arena -size 9` was enough; it is not. Co-Authored-By: Claude Fable 5.2 --- docs/training.md | 9 +++++++-- training/export.py | 14 ++++++++++---- training/tests/test_loop.py | 16 ++++++++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/docs/training.md b/docs/training.md index 046bfb9..9e932a5 100644 --- a/docs/training.md +++ b/docs/training.md @@ -105,8 +105,13 @@ the board: `temp_moves`, and the replay window (`window_min`, `window_growth`, `window_max`), since a 13×13 game yields more rows than a 9×9 game. A network trained on only the new size from then on is not trained on the old -one any more; measure it there (`gofer arena -size 9` against the old run's -champion) before calling it a network for both. +one any more; measure it there before calling it a network for both. An ONNX +file plays one board size, so export the checkpoint for the old size first: + +```bash +.venv/bin/python -m training.export runs/13x13/ckpt/gen-0036.pt /tmp/13x13-gen-0036-on-9x9.onnx --size 9 +bin/gofer arena -size 9 -a nn:/tmp/13x13-gen-0036-on-9x9.onnx -b nn:runs/9x9/models/gen-0044.onnx -games 100 -visits 200 +``` ## Champions and releases diff --git a/training/export.py b/training/export.py index 7a040d7..f21b4dd 100644 --- a/training/export.py +++ b/training/export.py @@ -87,18 +87,24 @@ def verify_onnx(model: GoferNet, path: Path, atol: float = 1e-3) -> None: raise RuntimeError(f"ONNX export of {path} does not match PyTorch") -def main() -> None: +def main(argv: list[str] | None = None) -> None: ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("checkpoint", type=Path) ap.add_argument("out", type=Path) - args = ap.parse_args() + ap.add_argument("--size", type=int, default=0, + help="board size to export for (default: the checkpoint's own). An ONNX file plays one " + "size; the weights are the same for every size") + args = ap.parse_args(argv) from training.model import ModelConfig ck = torch.load(args.checkpoint, map_location="cpu", weights_only=False) - model = GoferNet(ModelConfig(**ck["model_config"])) + cfg = ModelConfig(**ck["model_config"]) + if args.size: + cfg.board_size = args.size + model = GoferNet(cfg) model.load_state_dict(ck["model"]) export(model, args.out) - print(f"wrote {args.out}") + print(f"wrote {args.out} ({cfg.board_size}x{cfg.board_size})") if __name__ == "__main__": diff --git a/training/tests/test_loop.py b/training/tests/test_loop.py index ce0fff0..ed8f912 100644 --- a/training/tests/test_loop.py +++ b/training/tests/test_loop.py @@ -176,6 +176,22 @@ def test_a_run_can_start_on_a_larger_board_from_another_runs_network(tmp_path, m r.init() +def test_a_checkpoint_can_be_exported_for_another_board_size(tmp_path, capsys): + import onnxruntime as ort + + from training import export + + src = trained_checkpoint(tmp_path / "big-board.pt", size=13) + export.main([str(src), str(tmp_path / "own.onnx")]) + export.main([str(src), str(tmp_path / "small.onnx"), "--size", "9"]) + assert "(13x13)" in capsys.readouterr().out.splitlines()[0] + for name, size in (("own", 13), ("small", 9)): + sess = ort.InferenceSession(str(tmp_path / f"{name}.onnx"), providers=["CPUExecutionProvider"]) + policy, _ = sess.run(None, {"spatial": np.zeros((2, NUM_PLANES, size, size), np.float32), + "global": np.zeros((2, NUM_GLOBALS), np.float32)}) + assert policy.shape == (2, size * size + 1) + + def test_loop_refuses_a_starting_network_it_cannot_use(tmp_path, monkeypatch, capsys): src = trained_checkpoint(tmp_path / "small-board.pt") tiny = ["--set", "anchors=[]", "--set", "board_size=13", "--set", f"init_from={src}"]