"""Move training checkpoints off the box, and back on. This is what makes a relaunch survivable. THE PROBLEM IT SOLVES /home/marimo is an OVERLAY filesystem and has been wiped twice (RESUME 14). A checkpoint that only exists there is gone at the next relaunch - and so is every hour of training behind it. The notebook survives, but a 162 MB adapter cannot live in a notebook cell. So the checkpoints have to travel. WHAT IT DOES push uploads resume.pt (the optimizer state: the only thing that allows a CONTINUATION rather than a restart) plus adapter_best.pt / adapter_last.pt, then RE-DOWNLOADS one file and compares hashes. Records the revision of every push. pull restores a checkpoint into a run directory when the local copy is missing, so the trainer finds `resume.pt` and continues from its last step instead of step 0. status what is local, what is on the Hub, and which step each one records. TOKENS: pushing needs write access. PULLING DOES NOT - the repos are public, so a relaunched box can restore the last checkpoint without any credential, as long as one was ever pushed. That asymmetry is deliberate and is the whole reason `push` is wired into the trainer. """ import argparse, hashlib, json, os, subprocess, sys, time, urllib.request import pathlib from pathlib import Path W = Path("/home/marimo/dragon_fsds") REPO = os.environ.get("DRAGON_CKPT_REPO", "dragonlimited/dragon-state") PREFIX = "runs" def _token(): """The key, from the environment OR the project's own key file. Both paths matter: a cell launched from the notebook does not inherit the shell that ran the training, and the file is the convention this project already uses (box_autopilot_plan reads it). Without this, a notebook-driven push silently reported "no token" while a token existed. """ t = os.environ.get("HF_TOKEN_BOOT") or os.environ.get("HF_TOKEN") or "" if not t: p = pathlib.Path("/home/marimo/.hf_token_boot") if p.exists(): t = p.read_text().strip() return t TOKEN = _token() STATE = W / "checkpoint_sync_state.json" WANTED = ("resume.pt", "adapter_best.pt", "adapter_last.pt", "RUN_STATE.json") def sha(p): h = hashlib.sha256() with open(p, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 22), b""): h.update(chunk) return h.hexdigest() def _state(): return json.loads(STATE.read_text()) if STATE.exists() else {"runs": {}} def _save(st): STATE.write_text(json.dumps(st, indent=2)) def remote_head(path): """(exists, sha256) of a Hub file, without a token (the repos are public).""" url = f"https://huggingface.co/{REPO}/resolve/main/{path}" req = urllib.request.Request(url, headers={"Authorization": f"Bearer {TOKEN}"} if TOKEN else {}) try: data = urllib.request.urlopen(req, timeout=180).read() return True, hashlib.sha256(data).hexdigest(), data except Exception as e: return False, f"unreadable:{type(e).__name__}", None def run_state(run_dir): """The small sidecar that tells a resuming process where it got to.""" p = run_dir / "RUN_STATE.json" return json.loads(p.read_text()) if p.exists() else {} def push(run_dir, verbose=True): """Upload the run's checkpoints, verify by re-download, and skip anything unchanged. The skip matters: without it every notebook run re-uploads half a gigabyte per arm. The verification matters more: the first version checked for `resume.pt` specifically, so a run without one (v3) reported a failure it had not suffered. """ run = Path(run_dir).name files = [run_dir / f for f in WANTED if (run_dir / f).exists()] if not files: return {"run": run, "pushed": 0, "status": "nothing to push"} if not TOKEN: return {"run": run, "pushed": 0, "status": "PENDING - no token: push needs write access; pulling does not", "would_push": [f.name for f in files], "sizes": {f.name: f.stat().st_size for f in files}} try: prev = ((_state().get("runs") or {}).get(run) or {}).get("hashes", {}) or {} except Exception: prev = {} pushed, failed, skipped, verified, hashes = [], [], [], {}, {} for f in files: local_sha = sha(f); hashes[f.name] = local_sha if prev.get(f.name) == local_sha: skipped.append(f.name); verified[f.name] = True; continue dest = f"{PREFIX}/{run}/{f.name}" r = subprocess.run(f'hf upload {REPO} "{f}" "{dest}" --repo-type model', shell=True, capture_output=True, text=True, env={**os.environ, "HF_TOKEN": TOKEN}) if r.returncode == 0: pushed.append(f.name) ok, rhash, _ = remote_head(dest) verified[f.name] = bool(ok and rhash == local_sha) else: failed.append(f.name); verified[f.name] = False all_ok = bool(verified) and all(verified.values()) st = _state() st.setdefault("runs", {})[run] = {"last_push": time.strftime("%Y-%m-%d %H:%M:%S"), "pushed": pushed, "skipped_unchanged": skipped, "failed": failed, "verified": verified, "resume_round_trip_ok": verified.get("resume.pt"), "hashes": hashes, "local_step": run_state(run_dir).get("step")} _save(st) status = ("pushed and verified" if pushed and all_ok else "already up to date (nothing changed since the last push)" if skipped and not pushed else "pushed but NOT verified" if pushed else "nothing was pushed") return {"run": run, "pushed": pushed, "skipped_unchanged": skipped, "failed": failed, "files_considered": [f.name for f in files], "verified": verified, "round_trip_verified": all_ok, "status": status} def pull(run_dir, verbose=True): run = Path(run_dir).name run_dir.mkdir(parents=True, exist_ok=True) got = [] for name in WANTED: local = run_dir / name if local.exists() and local.stat().st_size > 0: continue ok, rhash, data = remote_head(f"{PREFIX}/{run}/{name}") if ok and data is not None: local.write_bytes(data) got.append({"file": name, "bytes": len(data), "sha256": rhash[:16]}) if got: st = _state(); st.setdefault("restores", []).append( {"run": run, "at": time.strftime("%Y-%m-%d %H:%M:%S"), "restored": got}) _save(st) return {"run": run, "restored": got, "resume_pt_present": (run_dir / "resume.pt").exists(), "step": run_state(run_dir).get("step"), "note": "pulled without a token: the repos are public"} def status(): rows = {} for d in sorted(W.glob("dragon-lora*")): if not d.is_dir(): continue local = {f: ((d / f).exists() and (d / f).stat().st_size) for f in WANTED} ok, rhash, _ = remote_head(f"{PREFIX}/{d.name}/resume.pt") rows[d.name] = {"local": {k: v for k, v in local.items() if v}, "step": run_state(d).get("step"), "on_hub": ok, "hub_matches_local": (ok and local.get("resume.pt") and rhash == sha(d / "resume.pt")), "last_push": _state().get("runs", {}).get(d.name, {}).get("last_push")} return rows def main(): ap = argparse.ArgumentParser() ap.add_argument("--push", metavar="RUN_DIR") ap.add_argument("--pull", metavar="RUN_DIR") ap.add_argument("--push-all", action="store_true") ap.add_argument("--pull-all", action="store_true") ap.add_argument("--status", action="store_true") a = ap.parse_args() if a.push: print(json.dumps(push(Path(a.push)), indent=2)) if a.pull: print(json.dumps(pull(Path(a.pull)), indent=2)) if a.push_all: results = [push(d) for d in sorted(W.glob("dragon-lora*")) if d.is_dir()] for r in results: print(json.dumps(r, indent=2)) # a vacuous all() over an empty list is how a PENDING run claims success - never again: # there must be at least one push, none may have failed, and every push must have verified. # every run that had something to send must have sent it AND verified it; runs with nothing # to send (dragon-lora, dragon-lora-rl) are not failures and not successes # runs with nothing to send (dragon-lora, dragon-lora-rl) are not failures and not # successes; the ones that HAD files must all have verified. The earlier version also # required every run to participate, which is why a correct push never wrote the marker. considered = [r for r in results if (r.get("files_considered") or r.get("would_push"))] allok = bool(considered) and all(r.get("round_trip_verified") for r in considered) if allok: (W / "checkpoint_push_all.done").write_text( json.dumps({"at": time.strftime("%Y-%m-%d %H:%M:%S"), "runs": [r["run"] for r in results]}, indent=2)) print("ALL CHECKPOINTS VERIFIED ON THE HUB -> checkpoint_push_all.done") if a.pull_all: for d in sorted(W.glob("dragon-lora*")): if d.is_dir(): print(json.dumps(pull(d), indent=2)) if a.status or not any([a.push, a.pull, a.push_all, a.pull_all, a.status]): print(json.dumps(status(), indent=2)) if __name__ == "__main__": main()