Download code/dev/diloco2.py from Asilarkness/chess-nets: direct link, hf CLI and curl.
- Browser
- Download file 28.7 kB
-
https://huggingface.co/Asilarkness/chess-nets/resolve/main/code/dev/diloco2.py
- Command line
-
hf download hf://Asilarkness/chess-nets/code/dev/diloco2.py
-
curl -L -o diloco2.py https://huggingface.co/Asilarkness/chess-nets/resolve/main/code/dev/diloco2.py
28.7 kB
| """diloco.py <prep_dir> <run>: one DiLoCo worker (Douillard et al. 2023, "DiLoCo: Distributed Low-Communication | |
| Training of Language Models") training the chess net together with the other workers through the private Hugging Face | |
| repo $REPO, which is also the checkpoint store. Boxes cannot reach each other, so the Hub is the only channel. | |
| Round r: every worker loads the global weights theta(r), runs H inner AdamW steps on its own random batches and | |
| uploads its pseudo-gradient delta = theta(r) - theta_local (bf16) plus its BatchNorm running statistics to | |
| diloco/<run>/r<r>/w<WID>.pt. The leader waits for the deltas of the live workers (at most WAIT s after its own) and | |
| writes r<r>/used.json = the list it used. Every worker then applies the same outer step on the CPU in fp32: mean of | |
| the used deltas, SGD with Nesterov momentum (lr OLR, momentum 0.9), BN statistics averaged -> theta(r+1), bit-identical | |
| on all workers. Every CK rounds the leader uploads ckpt/global.pt (theta, outer momentum, round) + nets/<run>16.pt.gz | |
| (fp16 net for play) + status.json (internal val metrics), and deletes the round folders the checkpoint made obsolete. | |
| A worker that starts (or restarts on a new box) loads the latest global.pt and replays the later rounds from their | |
| used.json and deltas, then joins at the next round (announced in join/w<WID>.json), so a dead box loses only its | |
| current round. A follower that sees no used.json for TAKEOVER s takes over as leader (leader.json). | |
| env: WID, REPO, H (inner steps per round), TOTAL (inner steps per worker for the whole schedule), LR (inner peak), | |
| OLR, BS, C, NB, NA, CF, INIT (start weights if the run has no checkpoint yet), COMPILE, WAIT, TAKEOVER, CK, VAL, | |
| PREP2 / PV_MAX / PV_FRAC (extra packed data, see load()), AUX=1 (two auxiliary PV-move heads, chessnet AUX; targets | |
| mv2 / mv3 from fastprep) with loss weight AUX_W (0 = heads present but untrained: the same net, data and cost as a | |
| baseline). Without INIT a new run starts from random weights. | |
| Hard-example selection: SEL=loss draws POOL*BS positions per step, scores them with the current net (no grad) and | |
| trains on the BS with the highest loss (selective backprop); SEL=rho scores by the reducible loss = current loss minus | |
| the loss of a trained model IL_CKPT (RHO-LOSS, Mindermann et al. 2022: learnable, worth learning, not yet learnt; noisy | |
| or ambiguous labels score low because the trained model gets them wrong too). BUDGET_MIN: after the second round TOTAL | |
| is reset so that training ends after that many minutes (a fair same-wall-clock comparison of slower steps). | |
| Writes the final weights to ckpt_<run>.pt and prints DILOCO_DONE.""" | |
| import glob, io, json, math, os, sys, threading, time | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from huggingface_hub import CommitOperationAdd, CommitOperationDelete, HfApi, hf_hub_download | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from chessnet import Net, planes_packed | |
| prep, run = sys.argv[1], sys.argv[2] | |
| E = os.environ.get | |
| WID, REPO = int(E("WID", 0)), E("REPO") | |
| H, TOTAL, LR, OLR = int(E("H", 1000)), int(E("TOTAL", 60000)), float(E("LR", 1e-3)), float(E("OLR", 0.7)) | |
| B, C, NB, NA, CF = int(E("BS", 4096)), int(E("C", 256)), int(E("NB", 12)), int(E("NA", 6)), int(E("CF", 1)) | |
| WAIT, TAKEOVER, CK = float(E("WAIT", 300)), float(E("TAKEOVER", 900)), int(E("CK", 5)) | |
| AUX, AUX_W = int(E("AUX", 0)), float(E("AUX_W", 0.5)) | |
| ARCH = E("ARCH", "") # archzoo.py net (architecture tournament, e.g. V46: legal-move policy); needs TEACHER (its legal list is the net's input) | |
| if ARCH: | |
| import archzoo | |
| def cl(x): | |
| return x if ARCH else x.to(memory_format=torch.channels_last) | |
| # TEACHER=<lc0 .f16.onnx>: online distillation (teacher.py). Policy loss = TMIX * cross-entropy to the teacher's policy | |
| # over the legal moves + (1 - TMIX) * the usual one to Stockfish's move; value target = VMIX * teacher W + D/2 + | |
| # (1 - VMIX) * Stockfish's expected score. | |
| TEACHER, TMIX, VMIX = E("TEACHER", ""), float(E("TMIX", 0.8)), float(E("VMIX", 0.7)) | |
| # DAG=1: DAgger positions (dag.py) - every round our own policy plays from data positions, the teacher labels what it reaches; | |
| # DAG_BD of them join every batch (drawn where our net is wrong), loss weight DAG_W * BD / B, teacher targets only. | |
| DAG, DAG_BD, DAG_W = int(E("DAG", 0)), int(E("DAG_BD", 1024)), float(E("DAG_W", 1.0)) | |
| # DAG_SRC=trees (dist6): the DAG rows are nodes of Lc0-teacher SEARCH trees on positions of our games (treegen.py shards): the | |
| # value target is the subtree's Q, the policy target the visit distribution (nodes with many visits); waits <= DAG_WAIT s for them. | |
| DAG_TREES, DAG_WAIT = E("DAG_SRC", "") == "trees", float(E("DAG_WAIT", 2400)) | |
| SEL, POOL = E("SEL", ""), int(E("POOL", 2)) | |
| VAL = int(E("VAL", CK)) # val metrics every VAL rounds, checkpoints every CK | |
| BPP = 42 if AUX else 38 # bytes per position on the GPU | |
| MOM = float(E("MOM", 0.9)) # outer momentum (0 + OLR 1 = plain parameter averaging of the workers) | |
| ROOT = f"diloco/{run}" | |
| CACHE = E("OUT_DIR", "/marimo/chess") + "/hfcache" | |
| api = HfApi() | |
| torch.backends.cudnn.benchmark = True | |
| torch.backends.cuda.matmul.allow_tf32 = torch.backends.cudnn.allow_tf32 = True | |
| def log(*a): | |
| print(time.strftime("%H:%M:%S"), f"w{WID}", *a, flush=True) | |
| def retry(f, what, tries=10): | |
| i = 0 | |
| while True: | |
| try: | |
| return f() | |
| except Exception as e: | |
| full = str(e) | |
| if "storage limit" in full.lower(): # the account's HF storage is full: wait until space is freed | |
| if i % 10 == 0: | |
| log(f"{what}: HF private storage limit reached, waiting for free space ({i} min)") | |
| time.sleep(60) | |
| i += 1 | |
| continue | |
| log(f"{what} failed ({type(e).__name__}: {full[:150]}), retry {i + 1}") | |
| i += 1 | |
| if i >= tries: | |
| raise RuntimeError(what + " failed for good") | |
| time.sleep(min(60, 3 * 2 ** i)) | |
| def ls(path): | |
| """Names of the files directly in a repo folder ([] if it does not exist).""" | |
| try: | |
| return [os.path.basename(f.path) for f in api.list_repo_tree(REPO, path_in_repo=path)] | |
| except Exception: | |
| return [] | |
| def get(path): | |
| return retry(lambda: hf_hub_download(REPO, path, cache_dir=CACHE), "download " + path) | |
| def put(ops, msg): | |
| retry(lambda: api.create_commit(REPO, operations=ops, commit_message=msg), "commit " + msg) | |
| def blob(obj): | |
| b = io.BytesIO() | |
| torch.save(obj, b) | |
| return b.getvalue() | |
| def add(path, data): | |
| return CommitOperationAdd(path_in_repo=path, path_or_fileobj=data) | |
| # ---- data, held entirely on the GPU in the packed form (chessnet.pack: 38 bytes per position). Root positions | |
| # (prep_dir, prep.py format) keep the same val split on every worker and in every run; PREP2 adds packed sets | |
| # (prep_pv.py: positions along Stockfish's PV, ply <= PV_MAX), drawn as a PV_FRAC share of every batch. | |
| def pack_gpu(b): | |
| sh = torch.arange(64, device=b.device) | |
| ids = torch.zeros(b.shape[0], 64, dtype=torch.uint8, device=b.device) | |
| for k in range(12): | |
| ids += (((b[:, k:k + 1] >> sh) & 1) * (k + 1)).to(torch.uint8) | |
| return ids[:, 0::2] | (ids[:, 1::2] << 4) | |
| def load(groups): | |
| """groups [(dirs, ply_max or None)] -> GPU tensors pk [N, 32] u8, fl / mv [N] int16, v [N] f16 holding all groups | |
| one after the other (allocated once: no concatenation peak), and the number of positions and parts per group.""" | |
| plan = [] | |
| for g, (dirs, ply_max) in enumerate(groups): | |
| for f in sorted(f for d in dirs for f in glob.glob(f"{d}/part_*.npz")): | |
| z = np.load(f) # first pass: sizes (+ the PV-ply filter) to preallocate | |
| k = None if ply_max is None else ((z["fl"].astype(np.int64) >> 9) & 15) <= ply_max | |
| plan.append((f, k, len(z["v"]) if k is None else int(k.sum()), g)) | |
| n = sum(m for _, _, m, _ in plan) | |
| budget = float(E("DATA_GB", 58)) * 2 ** 30 / BPP # positions that fit next to training | |
| n0 = sum(m for _, _, m, g in plan if g == 0) | |
| if n > budget and n > n0: # too many: keep a random share of the extra groups | |
| frac = max(0.0, (budget - n0) / (n - n0)) | |
| rng = np.random.default_rng(WID) | |
| plan2 = [] | |
| for f, k, m, g in plan: | |
| if g > 0: | |
| k = (np.ones(len(np.load(f)["v"]), bool) if k is None else k) & (rng.random(len(k if k is not None else np.load(f)["v"])) < frac) | |
| m = int(k.sum()) | |
| plan2.append((f, k, m, g)) | |
| plan = plan2 | |
| n = sum(m for _, _, m, _ in plan) | |
| log(f"data over {E('DATA_GB', 58)} GB: keeping {frac:.0%} of the extra positions") | |
| out = dict(pk=torch.empty(n, 32, dtype=torch.uint8, device="cuda"), fl=torch.empty(n, dtype=torch.int16, device="cuda"), | |
| mv=torch.empty(n, dtype=torch.int16, device="cuda"), v=torch.empty(n, dtype=torch.float16, device="cuda")) | |
| if AUX: | |
| out["mv2"], out["mv3"] = torch.empty(n, dtype=torch.int16, device="cuda"), torch.empty(n, dtype=torch.int16, device="cuda") | |
| i = 0 | |
| for f, k, m, _ in plan: | |
| z = dict(np.load(f)) | |
| if k is not None: | |
| z = {a: b[k] for a, b in z.items()} | |
| out["pk"][i:i + m] = torch.from_numpy(z["pk"]).cuda() if "pk" in z else pack_gpu(torch.from_numpy(z["bb"]).cuda()) | |
| out["fl"][i:i + m] = torch.from_numpy(z["fl"].astype(np.int16) & 255).cuda() | |
| out["mv"][i:i + m] = torch.from_numpy(z["mv"].astype(np.int16)).cuda() | |
| out["v"][i:i + m] = torch.from_numpy(z["v"].astype(np.float16)).cuda() | |
| for a in ("mv2", "mv3") if AUX else (): # parts written before fastprep had them: no target | |
| if a in z: | |
| out[a][i:i + m] = torch.from_numpy(z[a].astype(np.int16)).cuda() | |
| else: | |
| out[a][i:i + m] = -1 | |
| i += m | |
| return out, [sum(m for _, _, m, gg in plan if gg == g) for g in range(len(groups))], [sum(1 for *_, gg in plan if gg == g) for g in range(len(groups))] | |
| PV_FRAC = float(E("PV_FRAC", 0.5)) if E("PREP2") else 0.0 | |
| groups = [([prep], None)] + ([(E("PREP2").split(","), int(E("PV_MAX", 8)))] if PV_FRAC else []) | |
| D, sizes, nparts = load(groups) | |
| N, N2 = sizes[0], (sizes[1] if PV_FRAC else 0) | |
| perm = torch.randperm(N, device="cuda", generator=torch.Generator(device="cuda").manual_seed(0)) | |
| NVAL = int(E("NVAL", 100_000)) # (smaller only for local smoke tests) | |
| val_idx, tr_idx = perm[:NVAL], perm[NVAL:] | |
| del perm | |
| if PV_FRAC: | |
| log(f"+ {N2:,} PV positions from {nparts[1]} parts (ply <= {E('PV_MAX', 8)}), {PV_FRAC:.0%} of every batch") | |
| gen = torch.Generator(device="cuda").manual_seed(1009 * WID + int(time.time()) % 100_000) | |
| log(f"{N:,} positions from {nparts[0]} parts; GPU memory {torch.cuda.memory_allocated() / 2 ** 30:.1f} GB") | |
| if TEACHER: | |
| from teacher import Teacher | |
| teach = Teacher(TEACHER, int(E("TB", 1024))) | |
| log(f"teacher {TEACHER} (TMIX {TMIX}, VMIX {VMIX})") | |
| if DAG: | |
| assert TEACHER and not int(E("PLY1", 0)), "DAG needs the teacher and excludes PLY1" | |
| from dag import Dag, TreeStore, wait_shards | |
| dag = TreeStore(wait_shards(DAG_WAIT, log)) if DAG_TREES else Dag(int(E("DAG_PASSES", 32)), 2048, int(E("DAG_L", 12)), float(E("DAG_T", 0.8))) | |
| if DAG_TREES: | |
| log(f"dag trees: {DAG_BD} rows per batch from {len(dag.q):,} tree nodes ({int((dag.ppos >= 0).sum()):,} with a visit policy)") | |
| else: | |
| log(f"dag: {DAG_BD} positions per batch, rollouts of {dag.L} plies, {dag.passes} x {dag.R} per round") | |
| torch.manual_seed(int(E("SEED", 0))) # the same random init in every run of a comparison | |
| assert not ARCH or (E("TEACHER") and not AUX and not int(E("DAG", 0)) and not int(E("PLY1", 0))), "ARCH needs TEACHER and no AUX / DAG / PLY1" | |
| net = archzoo.make(ARCH).cuda() if ARCH else Net(C, NB, NA, CF, AUX).cuda().to(memory_format=torch.channels_last) | |
| fwd = torch.compile(net) if E("COMPILE") else net | |
| PLY1 = int(E("PLY1", 0)) # "check one move ahead" (ply1.py) | |
| if PLY1: | |
| from ply1 import Ply1 | |
| ply = Ply1(net, int(E("PLY1_S", 1024)), int(E("PLY1_K", 8)), int(E("PLY1_NQ", 1024)), float(E("PLY1_TAU", 0.05)), | |
| float(E("PLY1_M", 0.02))) | |
| PLY1_P, PLY1_V = float(E("PLY1_P", 0.5)), float(E("PLY1_V", 1.0)) | |
| P = dict(net.named_parameters()) | |
| BUF = {k: t for k, t in net.named_buffers() if t.is_floating_point() and k in net.state_dict()} | |
| decay = [p for n, p in P.items() if p.ndim > 1] | |
| rest = [p for n, p in P.items() if p.ndim <= 1] | |
| opt = torch.optim.AdamW([{"params": decay, "weight_decay": 1e-4}, {"params": rest, "weight_decay": 0}], lr=LR, fused=True) | |
| def batch(idx): | |
| x = cl(planes_packed(D["pk"][idx], D["fl"][idx].long())) | |
| if AUX: | |
| return x, D["mv"][idx].long(), D["v"][idx].float(), D["mv2"][idx].long(), D["mv3"][idx].long() | |
| return x, D["mv"][idx].long(), D["v"][idx].float() | |
| def sample(n=B): | |
| n2 = int(n * PV_FRAC) | |
| idx = tr_idx[torch.randint(0, len(tr_idx), (n - n2,), device="cuda", generator=gen)] | |
| if n2: | |
| idx = torch.cat([idx, N + torch.randint(0, N2, (n2,), device="cuda", generator=gen)]) | |
| return idx | |
| def dag_roots(n): | |
| idx = sample(n) | |
| return cl(planes_packed(D["pk"][idx], D["fl"][idx].long())), D["fl"][idx] | |
| def per_sample_loss(pol, val, m, t): | |
| return F.cross_entropy(pol.float(), m, reduction="none") + 1.5 * F.binary_cross_entropy_with_logits(val.float(), t, reduction="none") | |
| if SEL == "rho": # the irreducible-loss model: frozen, eval mode | |
| from chessnet import make_net | |
| _d = torch.load(E("IL_CKPT", "/marimo/chess/ckpt_hyb2.pt"), map_location="cpu") | |
| il = make_net(_d).cuda().eval().to(memory_format=torch.channels_last) | |
| il.load_state_dict({k: t.float() if t.is_floating_point() else t for k, t in _d["state"].items()}) | |
| il_fwd = torch.compile(il) if E("COMPILE") else il | |
| del _d | |
| def select(): | |
| """POOL*B candidates -> the B with the highest (reducible) loss under the current net (eval-mode BN, no grad).""" | |
| idx = sample(B * POOL) | |
| x, m, t, *_ = batch(idx) | |
| net.eval() | |
| with torch.no_grad(), torch.autocast("cuda", torch.bfloat16): | |
| pol, val = fwd(x) | |
| sc = per_sample_loss(pol, val, m, t) | |
| if SEL == "rho": | |
| p2, v2 = il_fwd(x) | |
| sc = sc - per_sample_loss(p2, v2, m, t) | |
| net.train() | |
| return idx[sc.topk(B).indices] | |
| def evaluate(): | |
| net.eval() | |
| acc = vl = 0.0 | |
| ax = [0.0, 0.0, 0, 0] # aux heads: hits, positions with a target | |
| with torch.no_grad(), torch.autocast("cuda", torch.bfloat16): | |
| CH = 8192 if ARCH else 10_000 # ARCH: the teacher gives the legal list (batches of a multiple of its TB; NVAL=98304 = 12 x 8192) | |
| for i in range(0, len(val_idx), CH): | |
| bi = val_idx[i:i + CH] | |
| x, m, t, *am = batch(bi) | |
| pol, val, *al = net(x, aux=True) if AUX else (net(x, teach(x, D["fl"][bi])[0]) if ARCH else net(x)) | |
| acc += (pol.float().argmax(1) == m).float().sum().item() | |
| vl += F.binary_cross_entropy_with_logits(val.float(), t, reduction="sum").item() | |
| for j in range(len(al)): | |
| ax[j] += ((al[j].float().argmax(1) == am[j]) & (am[j] >= 0)).float().sum().item() | |
| ax[2 + j] += (am[j] >= 0).sum().item() | |
| net.train() | |
| global aux_acc | |
| aux_acc = [round(ax[j] / max(ax[2 + j], 1), 4) for j in range(2)] if AUX else None | |
| return round(acc / len(val_idx), 4), round(vl / len(val_idx), 4) | |
| # ---- global state: theta (fp32, CPU) for parameters + float buffers, outer momentum for parameters | |
| def load_theta(): | |
| with torch.no_grad(): | |
| for k, t in P.items(): | |
| t.copy_(theta[k]) | |
| for k, t in BUF.items(): | |
| t.copy_(theta[k]) | |
| def outer(r, used, deltas): | |
| """theta(r) -> theta(r+1) from the deltas of the workers in `used` (sorted, so the sums are identical).""" | |
| for k in P: | |
| g = sum(deltas[w]["d"][k].float() for w in used) / len(used) | |
| mom[k].mul_(MOM).add_(g) | |
| theta[k].sub_(OLR * (g + MOM * mom[k])) | |
| for k in BUF: | |
| theta[k] = sum(deltas[w]["b"][k].float() for w in used) / len(used) | |
| def fetch_deltas(r, used, own=None): | |
| d = {} | |
| for w in used: | |
| d[w] = own if (own is not None and w == WID) else torch.load(get(f"{ROOT}/r{r:05d}/w{w}.pt"), map_location="cpu") | |
| return d | |
| def leader(): | |
| if "leader.json" in ls(ROOT): | |
| return json.load(open(get(f"{ROOT}/leader.json")))["wid"] | |
| return 0 | |
| # start: latest checkpoint, or create the run from INIT (worker 0) | |
| while "global.pt" not in ls(f"{ROOT}/ckpt"): | |
| if WID == 0: | |
| if not E("INIT"): # from scratch (random init) | |
| st0 = None | |
| elif E("INIT").startswith("hf:"): # another run's checkpoint in the repo, e.g. hf:diloco/hyb1/ckpt/global.pt | |
| st0 = torch.load(get(E("INIT")[3:]), map_location="cpu")["theta"] | |
| else: | |
| st0 = torch.load(E("INIT"), map_location="cpu")["state"] | |
| if st0 is not None: | |
| net.load_state_dict({k: t.float() if t.is_floating_point() else t for k, t in st0.items()}, strict=False) | |
| st = net.state_dict() | |
| g0 = {"theta": {k: st[k].float().cpu() for k in list(P) + list(BUF)}, | |
| "mom": {k: torch.zeros_like(P[k], device="cpu") for k in P}, "round": 0} | |
| put([add(f"{ROOT}/ckpt/global.pt", blob(g0))], f"{run}: start from {E('INIT')}") | |
| log("created the run from", E("INIT")) | |
| else: | |
| log("waiting for the run's first checkpoint") | |
| time.sleep(30) | |
| g = torch.load(get(f"{ROOT}/ckpt/global.pt"), map_location="cpu") | |
| theta, mom, r = g["theta"], g["mom"], g["round"] | |
| log("checkpoint at round", r) | |
| fresh = r == 0 and "used.json" not in ls(f"{ROOT}/r00000") | |
| while True: # replay the rounds finished after the checkpoint | |
| names = ls(f"{ROOT}/r{r:05d}") | |
| if "used.json" not in names: | |
| break | |
| used = json.load(open(get(f"{ROOT}/r{r:05d}/used.json"))) | |
| outer(r, used, fetch_deltas(r, used)) | |
| r += 1 | |
| log("replayed up to round", r) | |
| lead = leader() | |
| if not fresh and r * H < TOTAL: # others may be inside round r: wait for it to close, then join r + 1 | |
| t_w, used = time.time(), None | |
| while True: | |
| names = ls(f"{ROOT}/r{r:05d}") | |
| if "used.json" in names: | |
| used = json.load(open(get(f"{ROOT}/r{r:05d}/used.json"))) | |
| break | |
| if lead != WID and time.time() - t_w > TAKEOVER: # nobody closes it: the leader is gone | |
| put([add(f"{ROOT}/leader.json", json.dumps({"wid": WID, "round": r}).encode())], f"{run}: w{WID} takes over at r{r}") | |
| lead = WID | |
| log("took over as leader at round", r) | |
| if lead == WID: # we are the leader: close it with what is there | |
| used = sorted(int(n[1:-3]) for n in names if n.startswith("w") and n.endswith(".pt")) | |
| if used: | |
| put([add(f"{ROOT}/r{r:05d}/used.json", json.dumps(used).encode())], f"{run}: r{r} used {used} (restart)") | |
| break | |
| time.sleep(10) | |
| if used: | |
| outer(r, used, fetch_deltas(r, used)) | |
| r += 1 | |
| if r * H < TOTAL: # (a finished run only writes its weights below) | |
| put([add(f"{ROOT}/join/w{WID}.json", json.dumps({"round": r, "t": time.time()}).encode())], f"{run}: w{WID} joins r{r}") | |
| log("joining at round", r, "leader", lead) | |
| status = json.load(open(get(f"{ROOT}/status.json"))) if "status.json" in ls(ROOT) else {"history": []} | |
| step0, seen, ck_thread = r * H, {}, None | |
| t_train0, t_r1 = time.time(), None | |
| while r * H < TOTAL: | |
| load_theta() | |
| if PLY1: | |
| ply.refresh(net) | |
| if DAG: | |
| t_h = time.time() | |
| nd, sd, hd = dag.harvest(net, dag_roots, teach) if not DAG_TREES else (len(dag.q), 0.0, 0.0) | |
| log(f"dag: {nd:,} positions in {time.time() - t_h:.0f} s, mean score {sd:.3f}, share >= 0.3: {hd:.2f}") | |
| t0 = time.time() | |
| for i in range(H): | |
| s = r * H + i | |
| lr = LR * min(1.0, (s + 1) / 500, (s - step0 + 1) / 100) * (0.5 * (1 + math.cos(math.pi * min(s / TOTAL, 1))) * 0.98 + 0.02) | |
| for gr in opt.param_groups: | |
| gr["lr"] = lr | |
| bi = select() if SEL else sample() | |
| x, m, t, *am = batch(bi) | |
| if TEACHER: | |
| tli, tp, tv = teach(x, D["fl"][bi]) | |
| t = (VMIX * tv + (1 - VMIX) * t).clamp(0.0, 1.0) | |
| xin = x | |
| if PLY1: # + the offenders of the previous step (value bound only) | |
| xq, tq, wq = ply.extra(x) | |
| xin = torch.cat([x, xq]) | |
| if DAG: # + positions of our own play, labelled by the teacher | |
| xd, fd, *dx = dag.draw(DAG_BD) | |
| tdl, tdp, tdv = teach(xd, fd) | |
| if DAG_TREES: # the teacher's SEARCH result replaces its static output | |
| tdv, tdp = dx[0], torch.where(dx[2][:, None], dx[1], tdp) | |
| xin = torch.cat([x, xd]) | |
| with torch.autocast("cuda", torch.bfloat16): | |
| pol, val, *al = fwd(xin, aux=True) if AUX else (fwd(xin, tli) if ARCH else fwd(xin)) | |
| if PLY1: | |
| valq, pol, val, al = val[B:].float(), pol[:B], val[:B], [a[:B] for a in al] | |
| if DAG: | |
| pold, vald = pol[B:], val[B:] | |
| pol, val, al = pol[:B], val[:B], [a[:B] for a in al] | |
| lp = F.cross_entropy(pol.float().clamp(min=-30.0) if ARCH else pol.float(), m) # (ARCH: illegal slots hold -1e4) | |
| lv = F.binary_cross_entropy_with_logits(val.float(), t) | |
| if TEACHER: | |
| lt = -(tp * F.log_softmax(pol.float(), 1).gather(1, tli)).sum(1).mean() | |
| loss = TMIX * lt + (1 - TMIX) * lp + 1.5 * lv | |
| if DAG: | |
| ld = -(tdp * F.log_softmax(pold.float(), 1).gather(1, tdl)).sum(1).mean() | |
| lvd = F.binary_cross_entropy_with_logits(vald.float(), tdv.clamp(0.0, 1.0)) | |
| loss = loss + DAG_W * DAG_BD / B * (ld + 1.5 * lvd) | |
| else: | |
| loss = lp + 1.5 * lv | |
| if PLY1: | |
| slots, pi, pst = ply.look(x, D["fl"][bi], m, t, pol.detach()) | |
| ll = -(pi * F.log_softmax(pol[:ply.S].float(), 1).gather(1, slots)).sum(1).mean() | |
| lq = (F.binary_cross_entropy_with_logits(valq, tq, reduction="none") * (torch.sigmoid(valq) < tq) * wq).sum() / wq.sum().clamp(min=1) | |
| loss = loss + PLY1_P * ll + PLY1_V * lq | |
| if AUX: # opponent's reply and our next move on the PV (-1 = none) | |
| la = [(F.cross_entropy(a.float(), y.clamp(min=0), reduction="none") * (y >= 0)).sum() | |
| / (y >= 0).sum().clamp(min=1) for a, y in zip(al, am)] # 0, not NaN, without targets | |
| loss = loss + AUX_W * 0.5 * (la[0] + la[1]) | |
| opt.zero_grad(set_to_none=True) | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(net.parameters(), 2.0) | |
| opt.step() | |
| if i in (0, 3, 50, 300): | |
| log(f"inner step {i} at {time.time() - t0:.0f} s, loss {loss.item():.3f}") | |
| torch.cuda.synchronize() | |
| t_in = time.time() - t0 | |
| with torch.no_grad(): | |
| own = {"d": {k: (theta[k] - P[k].float().cpu()).to(torch.bfloat16) for k in P}, | |
| "b": {k: BUF[k].float().cpu() for k in BUF}, | |
| "loss": [round(lp.item(), 4), round(lv.item(), 4)] + ([round(a.item(), 4) for a in la] if AUX else []) | |
| + ([round(lt.item(), 4)] if TEACHER else []) | |
| + ([round(ld.item(), 4), round(lvd.item(), 4)] if DAG else []) | |
| + ([round(z.item(), 4) for z in (ll, lq, pst[0], pst[1])] if PLY1 else [])} | |
| put([add(f"{ROOT}/r{r:05d}/w{WID}.pt", blob(own))], f"{run}: r{r} w{WID}") | |
| t_up = time.time() | |
| lead = leader() | |
| if lead == WID: # wait for the live workers, then fix the set | |
| for n in ls(f"{ROOT}/join"): # a join counts as a delivery just before its round | |
| w = int(n[1:-5]) | |
| seen[w] = max(seen.get(w, -10 ** 9), json.load(open(get(f"{ROOT}/join/{n}")))["round"] - 1) | |
| expect = {w for w, sr in seen.items() if r - sr <= 2} | {WID} # dropped after missing 2 rounds | |
| while True: | |
| have = {int(n[1:-3]) for n in ls(f"{ROOT}/r{r:05d}") if n.startswith("w") and n.endswith(".pt")} | |
| if expect <= have or time.time() - t_up > WAIT: | |
| break | |
| time.sleep(5) | |
| used = sorted(have) | |
| seen.update({w: r for w in have}) | |
| put([add(f"{ROOT}/r{r:05d}/used.json", json.dumps(used).encode())], f"{run}: r{r} used {used}") | |
| else: | |
| while "used.json" not in ls(f"{ROOT}/r{r:05d}"): | |
| if time.time() - t_up > TAKEOVER: # the leader is gone: take over | |
| used = sorted(int(n[1:-3]) for n in ls(f"{ROOT}/r{r:05d}") if n.startswith("w") and n.endswith(".pt")) | |
| put([add(f"{ROOT}/leader.json", json.dumps({"wid": WID, "round": r}).encode()), | |
| add(f"{ROOT}/r{r:05d}/used.json", json.dumps(used).encode())], f"{run}: w{WID} takes over at r{r}") | |
| log("took over as leader at round", r) | |
| break | |
| time.sleep(5) | |
| used = json.load(open(get(f"{ROOT}/r{r:05d}/used.json"))) | |
| outer(r, used, fetch_deltas(r, used, own)) | |
| r += 1 | |
| if r == step0 // H + 1: | |
| t_r1 = time.time() | |
| elif r == step0 // H + 2 and E("BUDGET_MIN"): # rounds left in the budget at the measured round time | |
| per = time.time() - t_r1 | |
| TOTAL = r * H + H * max(1, int((float(E("BUDGET_MIN")) * 60 - (time.time() - t_train0)) / per)) | |
| log(f"budget {E('BUDGET_MIN')} min, {per:.0f} s per round: TOTAL -> {TOTAL}") | |
| msg = f"round {r} step {r * H}/{TOTAL} inner {t_in:.0f}s ({t_in / H * 1000:.0f} ms/step) sync {time.time() - t_up:.0f}s " \ | |
| f"used {used} lr {lr:.2e} loss {own['loss']}" | |
| if leader() == WID and (r % VAL == 0 or r % CK == 0 or r * H >= TOTAL): | |
| load_theta() | |
| acc, vl = evaluate() | |
| if not (acc >= (0.3 if r < 12 else 0.5) and vl <= 1.0): # healthy runs sit at ~0.58 / ~0.55 (a run from scratch needs ~12 rounds to get there): diverged -> stop before a checkpoint | |
| log(f"DIVERGED at round {r}: val top1 {acc} bce {vl} (no checkpoint written)") | |
| put([add(f"{ROOT}/DIVERGED.txt", f"round {r} top1 {acc} bce {vl}".encode())], f"{run}: DIVERGED at r{r}") | |
| os._exit(9) | |
| status["history"].append({"round": r, "step": r * H, "val_top1": acc, "val_bce": vl, "used": used, "t": time.time(), | |
| **({"val_aux": aux_acc} if AUX else {})}) | |
| msg += f" | VAL top1 {acc} value-bce {vl}" + (f" aux top1 {aux_acc}" if AUX else "") | |
| if r % CK == 0 or r * H >= TOTAL: # checkpoint upload (VAL < CK: val curve only) | |
| snap = {"theta": {k: t.clone() for k, t in theta.items()}, "mom": {k: t.clone() for k, t in mom.items()}, "round": r} | |
| half = {"C": C, "NB": NB, "NA": NA, "CF": CF, "AUX": AUX, "ARCH": ARCH, "step": r * H, "total": TOTAL, | |
| "state": {k: (t.half() if t.is_floating_point() else t).cpu() for k, t in net.state_dict().items()}} | |
| old = [n for n in ls(ROOT) if n.startswith("r") and n[1:].isdigit() and int(n[1:]) < r - 1] | |
| if ck_thread is not None: | |
| ck_thread.join() | |
| def upload(snap=snap, half=half, old=old, st=json.dumps(status).encode(), rr=r): | |
| import gzip | |
| put([add(f"{ROOT}/ckpt/global.pt", blob(snap)), add(f"nets/{run}16.pt.gz", gzip.compress(blob(half), 6)), | |
| add(f"{ROOT}/status.json", st)], f"{run}: checkpoint at round {rr}") | |
| if old: | |
| put([CommitOperationDelete(path_in_repo=f"{ROOT}/{n}/", is_folder=True) for n in old], f"{run}: drop old rounds") | |
| ck_thread = threading.Thread(target=upload) | |
| ck_thread.start() | |
| log(msg) | |
| if ck_thread is not None: | |
| ck_thread.join() | |
| load_theta() | |
| torch.save({"C": C, "NB": NB, "NA": NA, "CF": CF, "AUX": AUX, "ARCH": ARCH, "step": r * H, "total": TOTAL, "state": net.state_dict()}, | |
| f"{E('OUT_DIR', '/marimo/chess')}/ckpt_{run}.pt") | |
| log("DILOCO_DONE") | |