aboutsummaryrefslogtreecommitdiff
path: root/train/src/ctak_train/nn_train.py
blob: d2c2990e4fe0d3a5a70d20d5d60c8166910519e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#
# This file is part of ctak.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ctak. If not, see <https://www.gnu.org/licenses/>.

import argparse
import os
import subprocess
from pathlib import Path

import numpy as np

from ctak_train.candidate import Candidate, DataGenConfig, TrainingGridSearchConfig
from ctak_train.data import GameLog, load_window
from ctak_train.net import NET_DIMS
from ctak_train.selfplay import fan_out
from ctak_train.strength import fit_strengths, plot_strengths


def run_step(
    *,
    candidates: list[Candidate],
    data_gen_config: DataGenConfig,
    log: GameLog,
    strength_history: list[np.ndarray],
    iter: int,
):
    def data_path(i: int) -> Path:
        return (
            data_gen_config.root
            / "data"
            / f"selfplay-{data_gen_config.size}-v{i:03d}.json"
        )

    print(f"\n== iteration {iter} ==")

    num_candidates = len(candidates)
    cand_pairs = [
        (i, j) for i in range(num_candidates) for j in range(i, num_candidates)
    ]

    # 1. rebuild
    for i, j in cand_pairs:
        _ = subprocess.run(
            ["make", f"selfplay-{i}-{j}"],
            cwd=data_gen_config.root,
            check=True,
            capture_output=True,
        )

    # 2. generate self-play data
    data = data_path(iter)
    print(
        f"selfplay: {num_candidates=}, {data_gen_config.games=}, "
        f"{data_gen_config.size=}, {data_gen_config.depth=}, {data_gen_config.min_ply=}, "
        f"{data_gen_config.train_only_self_play=}"
    )
    out_games: list[str] = []
    for out in fan_out(
        [
            [
                f"./selfplay-{i}-{j}",
                str(data_gen_config.size),
                str(data_gen_config.depth),
                str(data_gen_config.min_ply),
            ]
            for (i, j) in cand_pairs
        ],
        data_gen_config.games,
        data_gen_config.procs,
        "selfplay",
        data_gen_config.root,
    ):
        out_games.extend(out.splitlines())
    print(f"writing {len(out_games):,} games to {data}")
    with open(data, "w") as f:
        _ = f.write("\n".join(out_games))
        if out_games:
            _ = f.write("\n")

    # 3. load the training window and append this iteration's games to the log
    data_files = [
        data_path(i)
        for i in range(max(iter - data_gen_config.replay_iters, 1), iter + 1)
    ]
    print("Loading data from", [str(c) for c in data_files], "...", end=" ")
    pools, new_games = load_window(
        data_files, data_gen_config.size, num_candidates, iter
    )
    print("candidates have", [f"{p.n_rows:,}" for p in pools], "rows.")
    log.append(new_games)

    # 4. fit strengths over the whole history, and plot the trajectory
    strengths, se = fit_strengths(log, num_candidates)
    strength_history.append(strengths)
    plot_strengths(
        strength_history,
        candidates,
        data_gen_config.root / "data" / "candidate_strength.png",
    )

    rated_games = int(np.count_nonzero(log.black != log.white))
    ranked = sorted(range(num_candidates), key=lambda i: strengths[i], reverse=True)
    print(
        f"Strength fit ({rated_games:,} head-to-head games, "
        f"iterations 1..{iter}, {rated_games // num_candidates:,} games/candidate):"
    )
    for idx in ranked:
        print(
            f"\tcandidate {idx:03d}: strength {strengths[idx]:6.1f} "
            f"± {1.96 * se[idx]:5.1f} Config {candidates[idx]}"
        )

    # 5. write champ, unconditionally
    idx = ranked[0]
    path = data_gen_config.root / "include" / f"weights_{data_gen_config.size}.c"
    candidates[idx].net.to_c(
        size=data_gen_config.size,
        ident=None,
        path=path,
        note=f"{iter=}, strength={strengths[idx]:.1f}",
    )
    _ = subprocess.run(
        ["make", "clean"], cwd=data_gen_config.root, check=True, capture_output=True
    )
    _ = subprocess.run(
        ["make", "native"], cwd=data_gen_config.root, check=True, capture_output=True
    )
    print(f"Wrote candidate {idx:03d} to {path!s}")

    # 6. fine-tune on the hybrid targets -> candidate
    for idx, cand in enumerate(candidates):
        corr, mse = cand.fit(pools[idx])
        cand.net.to_c(
            size=data_gen_config.size,
            ident=idx,
            path=data_gen_config.root
            / "include"
            / f"cand_{idx}_weights_{data_gen_config.size}.c",
            note=f"id={idx}, v{iter:03d}, val_corr={corr:.4f}, val_mse={mse:.4f}",
        )


def main() -> None:
    # repo root, relative to this file at <root>/train/src/ctak_train/nn_train.py
    root = Path(__file__).resolve().parents[3]
    p = argparse.ArgumentParser(
        description="Train the neural network evaluators of ctak",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    _ = p.add_argument(
        "--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(
        "--games",
        type=int,
        default=200,
        help="games per iteration",
    )
    _ = p.add_argument(
        "--replay-iters",
        type=int,
        default=10,
        help="number of previous data files to keep in the training pools "
        "(every game record is kept for the strength fit)",
    )
    _ = p.add_argument(
        "--smooth-factor",
        type=float,
        nargs="+",
        default=[0.3, 0.5, 0.7, 0.9],
        help="grid points for the EMA smoothing factor",
    )
    _ = p.add_argument(
        "--epochs",
        type=int,
        nargs="+",
        default=[5],
        help="grid points for candidate training epochs",
    )
    _ = p.add_argument(
        "--lr",
        type=float,
        nargs="+",
        default=[1e-4],
        help="grid points for learning rate",
    )
    _ = p.add_argument(
        "--batch",
        type=int,
        nargs="+",
        default=[128],
        help="grid points for training batch size",
    )
    _ = p.add_argument(
        "--val-frac",
        type=float,
        nargs="+",
        default=[0.05],
        help="grid points for fraction of rows held out for validation",
    )
    _ = p.add_argument(
        "--procs",
        type=int,
        default=None,
        help="parallel game processes (number of CPUs if unset)",
    )
    _ = p.add_argument(
        "--depth",
        type=int,
        default=4,
        help="search depth for selfplay and the matches",
    )
    _ = p.add_argument(
        "--min-ply",
        type=int,
        default=8,
        help="length of random opening in games",
    )
    _ = p.add_argument(
        "--train-all-games",
        action="store_true",
        help="train on all selfplay games, including matches between "
        "different candidates (default: self vs self games only)",
    )

    args = p.parse_args()

    # avoid counter-play start
    if args.min_ply < 2:
        _ = p.error("--min-ply must be >= 2")

    if args.procs is None:
        args.procs = max(1, (os.cpu_count() or 1))

    data_gen = DataGenConfig(
        size=args.size,
        depth=args.depth,
        min_ply=args.min_ply,
        games=args.games,
        procs=args.procs,
        replay_iters=args.replay_iters,
        root=root,
        train_only_self_play=not args.train_all_games,
    )
    tgsc = TrainingGridSearchConfig(
        smooth_factor=args.smooth_factor,
        epochs=args.epochs,
        batch=args.batch,
        lr=args.lr,
        val_frac=args.val_frac,
    )

    candidates = tgsc.make_configs(data_gen)

    (root / "data").mkdir(exist_ok=True)

    num_params = sum(
        p.numel() for p in candidates[0].net.parameters() if p.requires_grad
    )
    print(f"Number of trainable parameters: {num_params:,}")

    log = GameLog.empty()
    strength_history: list[np.ndarray] = []

    for iter in range(1, args.iters + 1):
        run_step(
            candidates=candidates,
            data_gen_config=data_gen,
            log=log,
            strength_history=strength_history,
            iter=iter,
        )
    print(f"\n== done, champion in include/weights_{args.size}.c ==")


if __name__ == "__main__":
    main()