Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
15 changes: 13 additions & 2 deletions cmd/gofer/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
28 changes: 22 additions & 6 deletions docs/training.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion internal/nn/features.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 10 additions & 3 deletions scripts/setup.sh
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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"
Expand Down
7 changes: 6 additions & 1 deletion training/elo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
64 changes: 45 additions & 19 deletions training/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from __future__ import annotations

import argparse
import contextlib
import logging
from pathlib import Path

import numpy as np
Expand All @@ -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:
Expand All @@ -22,43 +26,65 @@ 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)
tmp.replace(path)


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:
Expand Down
Loading
Loading