"""mkroots.py (box side, CPU only): roots for dist6 (treegen.py) and the held-out blunder test set, from the games of OUR nets. Games: HF results/evolve/games/*.json (our net = "gm3b256" vs Stockfish). Our nets: dist1 / ply1 / dist4 (amap.json: file -> net), series U box 0 (Ug0_*: dist4), series V (Vg*: dist5). The 6-ply opening of a game decides its fold (crc32 % 3): fold 0 -> training roots (treegen), folds 1 and 2 -> TEST (never trained on): the blunder test set and the held-out book. Outputs (written to /marimo/chess/dag6/, uploaded to HF code/): dag6_roots.json [{"fen", "g": "#", "ply", "prio"}], prio 1 = within 6 plies of one of our blunders (autopsy A/B), prio first, both groups shuffled dag6_test.json [{"fen", "g", "ply", "loss", "net"}]: our moves that lost >= 0.07 win probability (Stockfish judge), test folds openings_u_test.txt the test-fold lines of the unbalanced book (170 or so), for the final match python mkroots.py""" import io, json, os, random, zlib import chess, chess.pgn from huggingface_hub import HfApi, hf_hub_download as hd R, OUT = "Asilarkness/chess-nets", "/marimo/chess/dag6" os.makedirs(OUT, exist_ok=True) tok = open("/marimo/chess/.hf").read().strip().split()[-1].split("=")[-1].strip("'\"") api = HfApi(token=tok) files = [f.split("/")[-1] for f in api.list_repo_files(R) if f.startswith("results/evolve/games/")] here = os.path.dirname(os.path.abspath(__file__)) amap = json.load(open(os.path.join(here, "amap.json"))) def net_of(f): if f.startswith("Vg"): return "dist5" if f.startswith("Ug0_"): return "dist4" if f.startswith("Ug"): return "t3" return amap.get(f) def fold(key): return zlib.crc32(key.encode()) % 3 blund = {} # (file, gi) -> [(ply, loss)] of our moves, from the autopsy for tag in os.environ.get("AUTOPSY_TAGS", "A,B").split(","): try: for r in json.load(open(hd(R, f"results/autopsy/autopsy_{tag}.json", token=tok, local_dir="/marimo/chess/hf"))): blund[(r["file"], r["gi"])] = [(x[0], x[1]) for x in r["our"]] except Exception as e: print("autopsy", tag, type(e).__name__) roots, test, ng, nf = [], [], 0, [0, 0, 0] for f in sorted(files): net = net_of(f) if net not in ("dist1", "ply1", "dist4", "dist5"): continue games = json.load(open(hd(R, "results/evolve/games/" + f, token=tok, local_dir="/marimo/chess/hf")))["games"] for gi, z in enumerate(games): g = chess.pgn.read_game(io.StringIO(z["pgn"])) mv = list(g.mainline_moves()) if len(mv) < 8: continue key = " ".join(m.uci() for m in mv[:6]) fd = fold(key) nf[fd] += 1 ng += 1 bl = blund.get((f, gi), []) bad = [p for p, loss in bl if loss >= 0.07] b = g.board() for i in range(len(mv)): if fd == 0 and 30 <= i <= 125: roots.append({"fen": b.fen(), "g": f"{f}#{gi}", "ply": i, "prio": int(any(abs(i - p) <= 6 for p in bad))}) if fd != 0: for p, loss in bl: if p == i and loss >= 0.07: test.append({"fen": b.fen(), "g": f"{f}#{gi}", "ply": i, "loss": round(loss, 3), "net": net}) b.push(mv[i]) rng = random.Random(7) rng.shuffle(roots) roots.sort(key=lambda r: -r["prio"]) # stable: prio 1 first, each group shuffled if not os.environ.get("TEST_ONLY"): # TEST_ONLY=1: only the test positions (more autopsy tags), roots stay as trained on json.dump(roots, open(f"{OUT}/dag6_roots.json", "w")) json.dump(test, open(f"{OUT}/dag6_test.json", "w")) book = [l.strip() for l in open(hd(R, "code/openings_u.txt", token=tok, local_dir="/marimo/chess/hf")) if l.strip()] tb = [l for l in book if fold(l) != 0] open(f"{OUT}/openings_u_test.txt", "w").write("\n".join(tb) + "\n") print(f"games {ng} (folds {nf}), roots {len(roots)} (prio {sum(r['prio'] for r in roots)}), test positions {len(test)}, " f"book {len(book)} -> test lines {len(tb)}") from collections import Counter print("roots by net:", Counter(r["g"].split("#")[0][:2] for r in roots).most_common(5)) print("test by net:", Counter(t["net"] for t in test)) ops = [] from huggingface_hub import CommitOperationAdd for fn in (("dag6_test.json",) if os.environ.get("TEST_ONLY") else ("dag6_roots.json", "dag6_test.json", "openings_u_test.txt")): ops.append(CommitOperationAdd(path_in_repo="code/" + fn, path_or_fileobj=f"{OUT}/{fn}")) api.create_commit(R, ops, commit_message="dag6: roots / test positions / test book") print("MKROOTS_DONE")