aboutsummaryrefslogtreecommitdiff
path: root/src/nn_train.py
diff options
context:
space:
mode:
authortslil <tslil@posteo.de>2026-09-05 09:54:11 +0100
committertslil <tslil@posteo.de>2026-09-05 16:02:41 +0100
commitf6ea541ce762b190c7d68f221a24b555ebf0c80b (patch)
treee45e3d1fe740ed2c893cb7ee374ea99bd90f9d40 /src/nn_train.py
parent1ca3309dad9d412870b2b793f33af7a7ccabd514 (diff)
training rework, best weights so far*
After quite a bit of experimentation it would appear that a far better way to train on self-play data in this setup is to randomise not the moves but the opening. The new selfplay and match binaries have lost the epsilon parameter and now play a random opening of some length before switching to pure, deterministic engine inference. This also resulted in a cleanup of nn_train.py. As an added bonus, in this configuration it makes sense to harvest training data from both sides in self-play and consequently the two sides are given distinct game ids (this was almost surely an oversight in the original version of TD(lambda) that i had). I also noticed that rand32 was not using the top 32bits of xorshitf*. *Under default settings nn_train.py produces a 5x5 weight set that doesn't lose a single game to any other cttei that i cared to look at, when measured using `racetrack` (which has a diverse balanced opening book).
Diffstat (limited to 'src/nn_train.py')
-rwxr-xr-xsrc/nn_train.py152
1 files changed, 93 insertions, 59 deletions
diff --git a/src/nn_train.py b/src/nn_train.py
index 73a5eaf..e9a2d2c 100755
--- a/src/nn_train.py
+++ b/src/nn_train.py
@@ -239,7 +239,7 @@ class Net(Module):
train_targets = targets[train_idx]
# training widgets
- optimizer = torch.optim.Adam(self.parameters(), lr=lr)
+ optimizer = torch.optim.AdamW(self.parameters(), lr=lr)
loss_fn = MSELoss()
best_corr = -1.0
@@ -367,16 +367,16 @@ class TournamentResult:
def run_matches(
*,
- size: int,
depth: int,
- tournament_eps: float,
games: int,
procs: int,
root: Path,
+ size: int,
+ match_random_opening_length: int,
) -> TournamentResult:
outs = list(
fan_out(
- ["./match", str(size), f"{tournament_eps:.4f}", str(depth)],
+ ["./match", str(size), f"{match_random_opening_length}", str(depth)],
games,
procs,
"match",
@@ -413,12 +413,11 @@ def run_step(
champ: Net,
depth: int,
epochs: int,
- eps_decay: float,
- eps_min: float,
- eps_start: float,
games: int,
iter: int,
lr: float,
+ matches: int,
+ match_random_opening_length: int,
min_ply: int,
procs: int,
promote_rate: float,
@@ -426,8 +425,6 @@ def run_step(
root: Path,
size: int,
td_lambda: float,
- tournament_eps: float,
- tournament_games: int,
val_frac: float,
) -> Net:
def make_csv(i: int) -> Path:
@@ -435,16 +432,16 @@ def run_step(
print(f"\n== iteration {iter} ==")
- # 1. rebuild selfplay
+ # 1. rebuild
_ = subprocess.run(["make", "selfplay"], cwd=root, check=True, capture_output=True)
+ _ = subprocess.run(["make", "native"], cwd=root, check=True, capture_output=True)
# 2. generate self-play data
- eps = max(eps_min, eps_start * (eps_decay ** (iter - 1)))
csv = make_csv(iter)
- print(f"selfplay, eps={eps:.4f}, depth {depth}, {games} games on {procs} procs")
+ print(f"selfplay: {size=}, {depth=}, {min_ply=}")
out_rows: list[str] = []
for out in fan_out(
- ["./selfplay", str(size), f"{eps:.4f}", str(depth), str(min_ply)],
+ ["./selfplay", str(size), str(depth), str(min_ply)],
games,
procs,
"selfplay",
@@ -455,14 +452,13 @@ def run_step(
_ = f.write("\n".join(out_rows))
if out_rows:
_ = f.write("\n")
- rows = len(out_rows)
- print(f" {rows} rows")
# 3. fine-tune the champion on TD(lambda) targets -> candidate
device = next(champ.parameters()).device
csvs = [make_csv(i) for i in range(max(iter - replay_iters, 1), iter + 1)]
- print("Loading data from", [str(c) for c in csvs])
+ print("Loading data from", [str(c) for c in csvs], "...", end=" ")
records = SelfPlayRecords.load_merge(csvs, size, device)
+ print(f"{records.results.shape[0]:,} rows")
cand = copy.deepcopy(champ)
corr, mse = cand.fit(
@@ -483,21 +479,25 @@ def run_step(
# 4. build the match driver (champion + candidate)
_ = subprocess.run(["make", "match"], cwd=root, check=True, capture_output=True)
- # 5. tournament + decision
- tournament_result = run_matches(
- root=root,
- size=size,
- depth=depth,
- tournament_eps=tournament_eps,
- games=tournament_games,
- procs=procs,
- )
- decided = tournament_result.champ + tournament_result.cand
- rate = tournament_result.cand / decided if decided else 0.0
- print(
- f"champ {tournament_result.champ} - {tournament_result.cand} cand, {tournament_result.draws} draws, winrate={rate:.3f}"
- )
- promote = decided >= int(0.25 * tournament_games) and rate >= promote_rate
+ promote = True
+ rate = -1.0
+ if promote_rate > 0:
+ # 5. tournament + decision
+ print(f"match: {size=}, {match_random_opening_length=}, {depth=}")
+ tournament_result = run_matches(
+ depth=depth,
+ games=matches,
+ procs=procs,
+ root=root,
+ size=size,
+ match_random_opening_length=match_random_opening_length,
+ )
+ decided = tournament_result.champ + tournament_result.cand
+ rate = tournament_result.cand / decided if decided else 0.0
+ print(
+ f"champ {tournament_result.champ} - {tournament_result.cand} cand, {tournament_result.draws} draws, winrate={rate:.3f}"
+ )
+ promote = decided >= int(0.25 * matches) and rate > promote_rate
if promote:
cand.to_c(
@@ -523,16 +523,28 @@ def main() -> None:
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
_ = p.add_argument(
- "--size", type=int, choices=sorted(NET_DIMS), default=5, help="board size"
+ "--size",
+ type=int,
+ choices=sorted(NET_DIMS),
+ default=5,
+ help="board size",
+ )
+ _ = p.add_argument(
+ "--iters",
+ type=int,
+ default=100,
+ help="max loop iterations",
)
- _ = p.add_argument("--iters", type=int, default=10, help="max loop iterations")
_ = p.add_argument(
- "--games", type=int, default=100, help="selfplay games per iteration"
+ "--games",
+ type=int,
+ default=1000,
+ help="selfplay games per iteration",
)
_ = p.add_argument(
"--replay-iters",
type=int,
- default=0,
+ default=4,
help="number of previous self-play instances to mix in with current dataset during training",
)
_ = p.add_argument(
@@ -542,17 +554,41 @@ def main() -> None:
help="initial self-play epsilon: in asymmetric self-play one side (chosen at random per game) plays a uniform random move with this probability while the greedy side has its plies recorded",
)
_ = p.add_argument(
- "--eps-min", type=float, default=0.05, help="self-play epsilon floor"
+ "--eps-min",
+ type=float,
+ default=0.01,
+ help="self-play epsilon floor",
)
_ = p.add_argument(
- "--eps-decay", type=float, default=0.9, help="per-iteration epsilon decay"
+ "--eps-decay",
+ type=float,
+ default=0.9,
+ help="per-iteration epsilon decay",
)
- _ = p.add_argument("--td-lambda", type=float, default=0.6, help="TD(lambda) lambda")
_ = p.add_argument(
- "--epochs", type=int, default=20, help="candidate training epochs"
+ "--td-lambda",
+ type=float,
+ default=0.7,
+ help="TD(lambda) lambda",
+ )
+ _ = p.add_argument(
+ "--epochs",
+ type=int,
+ default=20,
+ help="candidate training epochs",
+ )
+ _ = p.add_argument(
+ "--lr",
+ type=float,
+ default=1e-4,
+ help="learning rate",
+ )
+ _ = p.add_argument(
+ "--batch",
+ type=int,
+ default=128,
+ help="training batch size",
)
- _ = p.add_argument("--lr", type=float, default=1e-3, help="learning rate")
- _ = p.add_argument("--batch", type=int, default=128, help="training batch size")
_ = p.add_argument(
"--val-frac",
type=float,
@@ -560,22 +596,22 @@ def main() -> None:
help="fraction of rows held out for validation",
)
_ = p.add_argument(
- "--tournament-eps",
- type=float,
- default=0.01,
- help="tournament epsilon (random-move probability)",
+ "--matchs",
+ type=int,
+ default=200,
+ help="how many matches in a tournament",
)
_ = p.add_argument(
- "--tournament-games",
+ "--match-random-opening-length",
type=int,
- default=None,
- help="tournament games (1/tournament-eps if unset)",
+ default=2,
+ help="length of random opening in a match",
)
_ = p.add_argument(
"--promote",
type=float,
- default=0.0,
- help="candidate win rate among non-drawn tournament games needed to promote",
+ default=0.53,
+ help="candidate win rate among non-drawn matches needed to promote",
)
_ = p.add_argument(
"--procs",
@@ -587,16 +623,17 @@ def main() -> None:
"--depth",
type=int,
default=4,
- help="search depth for selfplay and the tournament",
+ help="search depth for selfplay and the matches",
)
_ = p.add_argument(
- "--min-ply", type=int, default=4, help="record positions at this ply or later"
+ "--min-ply",
+ type=int,
+ default=8,
+ help="record positions at this ply or later",
)
args = p.parse_args()
- if args.tournament_games is None:
- args.tournament_games = max(100, int(round(1 / args.tournament_eps)))
if args.procs is None:
args.procs = max(1, (os.cpu_count() or 1) // 2)
@@ -608,12 +645,11 @@ def main() -> None:
champ=champ,
depth=args.depth,
epochs=args.epochs,
- eps_decay=args.eps_decay,
- eps_min=args.eps_min,
- eps_start=args.eps_start,
games=args.games,
iter=iter,
lr=args.lr,
+ matches=args.matches,
+ match_random_opening_length=args.match_random_opening_length,
min_ply=args.min_ply,
procs=args.procs,
promote_rate=args.promote,
@@ -621,8 +657,6 @@ def main() -> None:
root=root,
size=args.size,
td_lambda=args.td_lambda,
- tournament_eps=args.tournament_eps,
- tournament_games=args.tournament_games,
val_frac=args.val_frac,
)
print(f"\n== done, champion in include/weights_{args.size}.c ==")