chess-nets / code /dev /autopsy.py
Asilarkness's picture
dev files: autopsy.py
a3e4af6 verified
Raw History Blame Contribute Delete
5.83 kB
# autopsy.py <tag> <net:maxfiles,...> : Stockfish judge over the gauntlet games of our nets (box-side, CPU only)
import sys, os, io, json, math, time, random
import chess, chess.pgn, chess.engine
from multiprocessing import Pool
from huggingface_hub import HfApi, hf_hub_download as hd
tag = sys.argv[1]
want = {a.split(":")[0]: int(a.split(":")[1]) for a in sys.argv[2].split(",")}
NODES, NPROC, BOOK = 150000, int(os.environ.get("NPROC", 14)), 6
tok = open("/marimo/chess/.hf").read().strip().split()[-1].split("=")[-1].strip("'\"")
amap = json.load(open("/tmp/amap.json"))
for _f in HfApi(token=tok).list_repo_files("Asilarkness/chess-nets"): # series U (box 0 = dist4) and V (dist5) are not in amap.json
_b = os.path.basename(_f)
if _f.startswith("results/evolve/games/") and (_b.startswith("Vg") or _b.startswith("Ug0_") or _b.startswith("Wg")):
amap[_b] = "dist6" if _b.startswith("Wg") else "dist5" if _b.startswith("Vg") else "dist4"
ONLY = tuple(x for x in os.environ.get("ONLY_PREFIX", "").split(",") if x) # e.g. ONLY_PREFIX=Ug0_,Vg
R = "Asilarkness/chess-nets"
def wpf(cp): return 1 / (1 + math.exp(-0.00368208 * max(-1500, min(1500, cp))))
ENG = None
def init():
global ENG
ENG = chess.engine.SimpleEngine.popen_uci("/marimo/chess/sf")
ENG.configure({"Threads": 1, "Hash": 64})
def ev(b):
if b.is_game_over():
r = b.result()
return {"1-0": 1.0, "0-1": 0.0}.get(r, 0.5)
return wpf(ENG.analyse(b, chess.engine.Limit(nodes=NODES))["score"].white().score(mate_score=100000))
def work(a):
net, path, gi = a
z = json.load(open(path))["games"][gi]
g = chess.pgn.read_game(io.StringIO(z["pgn"]))
mv = list(g.mainline_moves()); b = g.board()
ow = z["white"] == "gm3b256"
res = z["result"]
w, fens = {}, {}
for i in range(len(mv) + 1):
if i >= BOOK: w[i] = ev(b); fens[i] = b.fen()
if i < len(mv): b.push(mv[i])
our, sf = [], []
for i in range(BOOK, len(mv)):
white = i % 2 == 0
bw, aw = (w[i], w[i + 1]) if white else (1 - w[i], 1 - w[i + 1])
rec = (i, max(0.0, bw - aw), bw)
(our if white == ow else sf).append(rec)
traj = {i: (w[i] if ow else 1 - w[i]) for i in w}
# san of our worst move
worst = max(our, key=lambda r: r[1]) if our else None
wsan = None
if worst:
bb = g.board()
for k in range(worst[0]): bb.push(mv[k])
wsan = [fens[worst[0]], bb.san(mv[worst[0]])]
return dict(net=net, file=os.path.basename(path), gi=gi, ow=ow, res=res, n=len(mv), our=our, sf=sf,
traj=[round(traj[i], 3) for i in sorted(traj)][::5], minwp=round(min(traj.values()), 3), worst=wsan)
def score_us(r): # 1 win, .5 draw, 0 loss for our net
s = {"1-0": 1.0, "0-1": 0.0}.get(r["res"], 0.5)
return s if r["ow"] else 1 - s
if __name__ == "__main__":
tasks = []
for net, mx in want.items():
fs = sorted(f for f, n in amap.items() if n == net and (not ONLY or f.startswith(ONLY)))[:mx]
for f in fs:
p = hd(R, "results/evolve/games/" + f, token=tok, local_dir="/marimo/chess/hf")
for gi in range(len(json.load(open(p))["games"])): tasks.append((net, p, gi))
random.Random(1).shuffle(tasks)
print("tasks", len(tasks), flush=True)
out, t0 = [], time.time()
with Pool(NPROC, initializer=init) as pool:
for k, r in enumerate(pool.imap_unordered(work, tasks, chunksize=1)):
out.append(r)
if k % 20 == 0: print(k, len(tasks), round(time.time() - t0), "s", flush=True)
json.dump(out, open(f"/tmp/autopsy_{tag}.json", "w"))
HfApi(token=tok).upload_file(path_or_fileobj=f"/tmp/autopsy_{tag}.json", path_in_repo=f"results/autopsy/autopsy_{tag}.json", repo_id=R, commit_message=f"autopsy {tag}")
for net in want:
rs = [r for r in out if r["net"] == net]
mo = sum(len(r["our"]) for r in rs); ms = sum(len(r["sf"]) for r in rs)
lo = sum(x[1] for r in rs for x in r["our"]); ls = sum(x[1] for r in rs for x in r["sf"])
b1 = sum(1 for r in rs for x in r["our"] if x[1] >= .1); b2 = sum(1 for r in rs for x in r["our"] if x[1] >= .2)
s1 = sum(1 for r in rs for x in r["sf"] if x[1] >= .1)
lost = [r for r in rs if score_us(r) == 0]
near = sum(1 for r in rs if score_us(r) > 0 and r["minwp"] < .2)
print(f"== {net}: {len(rs)} games, lost {len(lost)}, drawn games where our wp fell <0.2: {near}")
print(f" mean wp loss per move: ours {100 * lo / max(mo, 1):.2f} pts, SF {100 * ls / max(ms, 1):.2f} pts (SF judge flatters SF)")
print(f" blunders >=0.10 per 100 moves: ours {100 * b1 / max(mo, 1):.2f} (>=0.20: {100 * b2 / max(mo, 1):.2f}), SF {100 * s1 / max(ms, 1):.2f}")
for ph, (a, bnd) in {"6-40": (6, 40), "40-80": (40, 80), "80+": (80, 999)}.items():
xs = [x[1] for r in rs for x in r["our"] if a <= x[0] < bnd]
print(f" phase {ph}: {len(xs)} moves, mean loss {100 * sum(xs) / max(len(xs), 1):.2f} pts, blunders>=.1 {100 * sum(1 for v in xs if v >= .1) / max(len(xs), 1):.2f}%")
for r in sorted(lost, key=lambda r: r["file"]):
big = [x for x in r["our"] if x[1] >= .1]
first = big[0] if big else None
mx = max(r["our"], key=lambda x: x[1]) if r["our"] else None
drift = sum(x[1] for x in r["our"] if x[1] < .1)
print(f" LOST {r['file']}#{r['gi']} {'W' if r['ow'] else 'B'} plies {r['n']}: first blunder " +
(f"ply {first[0]} loss {first[1]:.2f} (wp before {first[2]:.2f})" if first else "none") +
f"; max single {mx[1]:.2f} @ {mx[0]}; small-loss drift {drift:.2f}; wp traj/5ply " + " ".join(f"{v:.1f}" for v in r["traj"][::2][:16]))
print("AUTOPSY_DONE", round(time.time() - t0), "s")