Download sync/sync_centre.py from davidwdw/b1k: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/davidwdw/b1k/resolve/main/sync/sync_centre.py
- Command line
-
hf download hf://datasets/davidwdw/b1k/sync/sync_centre.py
-
curl -L -o sync_centre.py https://huggingface.co/datasets/davidwdw/b1k/resolve/main/sync/sync_centre.py
12.2 kB
| #!/usr/bin/env python3 | |
| """Mirror B1K code and rollout results from Centre into this folder, re-runnable. | |
| Each source in SOURCES is rsynced (no --delete: files removed remotely are kept | |
| locally and flagged in the inventory). Full-state trajectory HDF5 files are | |
| ~3.6 GB each, so only those of runs marked `training_eligible` in the source's | |
| reports/*.json (plus EXTRA_HDF5 globs) are copied; every other file is listed in | |
| _sync/REMOTE_INVENTORY.tsv with its size, so nothing is silently missing. | |
| Every copied file is verified against a SHA-256 computed on Centre. Hashes are | |
| cached by (size, mtime), so re-runs only hash new or changed files. | |
| Usage: | |
| python3 sync/sync_centre.py # sync all sources | |
| python3 sync/sync_centre.py --dry-run # show what would transfer | |
| python3 sync/sync_centre.py --source task01_human_first_recovery | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import shlex | |
| import subprocess | |
| import sys | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| HOST = "centre" | |
| SOURCES = [ | |
| { | |
| "name": "task01_human_first_recovery", | |
| "remote": "/media/david/HDD/gpt6_b1k/task01_human_first_recovery", | |
| "dest": "task01_picking_up_trash/centre_human_first_recovery", | |
| # appdata: Isaac/Kit cache; rawdata: official human HDF5 (re-downloadable | |
| # from behavior-1k/2026-challenge-rawdata). | |
| "exclude": ["/appdata/", "/datasets/human/rawdata/", "/campaigns/", ".pytest_cache/", "__pycache__/"], | |
| "hdf5_eligible_from": "reports", | |
| "extra_hdf5": [], # e.g. "runs/official-zero20-v3/**/*.hdf5" | |
| }, | |
| { | |
| "name": "task01_demo_continuation", | |
| "remote": "/media/david/HDD/gpt6_b1k/task01_demo_continuation", | |
| "dest": "task01_picking_up_trash/centre_demo_continuation", | |
| "exclude": [], | |
| "hdf5_eligible_from": None, | |
| "extra_hdf5": [], | |
| }, | |
| { | |
| "name": "task01_recovery_primitive_filtered_20260921", | |
| "remote": "/media/david/HDD/task01_recovery_primitive_filtered_20260921", | |
| "dest": "task01_picking_up_trash/datasets/task01_recovery_primitive_filtered_20260921", | |
| "exclude": ["__pycache__/"], | |
| "copy_all_hdf5": True, | |
| }, | |
| { | |
| "name": "task01_vla_failure_recovery_20260918", | |
| "remote": "/media/david/HDD/gpt6_b1k/task01_human_first_recovery/campaigns/vla_failure_recovery_20260918", | |
| "dest": "task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918", | |
| "exclude": ["__pycache__/", ".pytest_cache/", "/state/", "/merge_test_20260919/"], | |
| "copy_all_hdf5": True, | |
| "snapshot_completed": True, | |
| }, | |
| ] | |
| def ssh(cmd, stdin=None): | |
| return subprocess.run(["ssh", "-o", "BatchMode=yes", HOST, cmd], input=stdin, | |
| capture_output=True, check=True).stdout | |
| def remote_inventory(src): | |
| prune = " -o ".join(f"-path ./{e.strip('/')}" for e in src["exclude"] if e.startswith("/")) | |
| names = " -o ".join(f"-name {e.strip('/')}" for e in src["exclude"] if not e.startswith("/")) | |
| skip = " -o ".join(x for x in (prune, names) if x) | |
| expr = f"\\( {skip} \\) -prune -o " if skip else "" | |
| out = ssh(f"cd {shlex.quote(src['remote'])} && find . {expr}-type f -printf '%P\\t%s\\t%T@\\n'") | |
| inv = {} | |
| for line in out.decode().splitlines(): | |
| path, size, mtime = line.split("\t") | |
| inv[path] = (int(size), int(float(mtime))) | |
| return inv | |
| def eligible_hdf5(src, inv): | |
| """HDF5 files inside runs that any reports/*.json marks training_eligible.""" | |
| wanted = set() | |
| if src["hdf5_eligible_from"]: | |
| script = f""" | |
| import json, glob | |
| runs = set() | |
| def walk(o): | |
| if isinstance(o, dict): | |
| if o.get('training_eligible') is True and isinstance(o.get('run'), str): | |
| runs.add(o['run']) | |
| for v in o.values(): walk(v) | |
| elif isinstance(o, list): | |
| for v in o: walk(v) | |
| for f in glob.glob('{src['hdf5_eligible_from']}/**/*.json', recursive=True): | |
| try: walk(json.load(open(f))) | |
| except Exception: pass | |
| print('\\n'.join(sorted(runs))) | |
| """ | |
| out = ssh(f"cd {shlex.quote(src['remote'])} && python3 -", stdin=script.encode()) | |
| prefix = src["remote"].rstrip("/") + "/" | |
| runs = [r[len(prefix):] if r.startswith(prefix) else r for r in out.decode().split()] | |
| for path in inv: | |
| if path.endswith(".hdf5") and any(path.startswith(r.rstrip("/") + "/") for r in runs): | |
| wanted.add(path) | |
| for pattern in src["extra_hdf5"]: | |
| wanted.update(p for p in inv if Path(p).match(pattern)) | |
| return wanted | |
| def rsync(src, dest, extra, dry): | |
| cmd = ["rsync", "-a", "--partial", "--info=stats1,progress2", "--no-inc-recursive"] | |
| cmd += ["--dry-run"] if dry else [] | |
| cmd += [f"--exclude={e}" for e in src["exclude"]] + extra | |
| cmd += [f"{HOST}:{src['remote'].rstrip('/')}/", f"{dest}/"] | |
| print("+", " ".join(shlex.quote(c) for c in cmd), flush=True) | |
| subprocess.run(cmd, check=True) | |
| def sha_local(path): | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for block in iter(lambda: f.read(1 << 22), b""): | |
| h.update(block) | |
| return h.hexdigest() | |
| def sha_remote(src, paths): | |
| if not paths: | |
| return {} | |
| out = ssh(f"cd {shlex.quote(src['remote'])} && xargs -0 sha256sum --", | |
| stdin=b"\0".join(p.encode() for p in paths)) | |
| result = {} | |
| for line in out.decode().splitlines(): | |
| digest, path = line.split(" ", 1) | |
| result[path] = digest | |
| return result | |
| def summarize_runs(dest, meta): | |
| """One row per top-level run directory, aggregated from its outcome.json files. | |
| `already_complete` counts starts whose restored initial state already satisfied | |
| the BDDL goal; they are excluded from `continued_success`. | |
| """ | |
| rows = {} | |
| for f in sorted((dest / "runs").glob("**/outcome.json")): | |
| top = f.relative_to(dest / "runs").parts[0] | |
| d = json.loads(f.read_text()) | |
| r = rows.setdefault(top, {"episodes": 0, "success": 0, "already_complete": 0, | |
| "errors": {}, "mtime": 0}) | |
| r["episodes"] += 1 | |
| already = bool((d.get("initial_task") or {}).get("success")) | |
| r["already_complete"] += already | |
| r["success"] += bool(d.get("success")) and not already | |
| if not d.get("success"): | |
| key = str(d.get("error") or d.get("status")) | |
| r["errors"][key] = r["errors"].get(key, 0) + 1 | |
| r["mtime"] = max(r["mtime"], int(f.stat().st_mtime)) | |
| lines = ["run\tlast_outcome_utc\tepisodes\talready_complete\tcontinued_success\tattempted\tsuccess_rate\ttop_failure"] | |
| for name, r in sorted(rows.items(), key=lambda kv: kv[1]["mtime"]): | |
| attempted = r["episodes"] - r["already_complete"] | |
| rate = f"{r['success'] / attempted:.3f}" if attempted else "" | |
| top = max(r["errors"].items(), key=lambda kv: kv[1])[0] if r["errors"] else "" | |
| when = datetime.fromtimestamp(r["mtime"], timezone.utc).strftime("%Y-%m-%dT%H:%MZ") | |
| lines.append(f"{name}\t{when}\t{r['episodes']}\t{r['already_complete']}\t{r['success']}" | |
| f"\t{attempted}\t{rate}\t{top}") | |
| (meta / "RUNS_SUMMARY.tsv").write_text("\n".join(lines) + "\n") | |
| def sync(src, dry): | |
| if src.get("copy_all_hdf5"): | |
| from sync_dataset_source import sync_dataset_source | |
| return sync_dataset_source(src, ROOT, dry=dry) | |
| dest = ROOT / src["dest"] | |
| meta = dest / "_sync" | |
| dest.mkdir(parents=True, exist_ok=True) | |
| meta.mkdir(exist_ok=True) | |
| started = datetime.now(timezone.utc).isoformat() | |
| inv = remote_inventory(src) | |
| hdf5 = eligible_hdf5(src, inv) | |
| print(f"[{src['name']}] remote files: {len(inv)}, eligible hdf5 to copy: {len(hdf5)}", flush=True) | |
| rsync(src, dest, ["--exclude=*.hdf5"], dry) | |
| if hdf5: | |
| listing = meta / "hdf5_selected.txt" | |
| listing.write_text("".join(p + "\n" for p in sorted(hdf5))) | |
| rsync(src, dest, [f"--files-from={listing}"], dry) | |
| if dry: | |
| return | |
| # Verify every local file against Centre, hashing only new/changed ones. | |
| cache_path = meta / "hash_cache.json" | |
| cache = json.loads(cache_path.read_text()) if cache_path.exists() else {} | |
| local = {} | |
| for p in dest.rglob("*"): | |
| # Production campaigns have their own registered source and checksum inventory. | |
| if "/campaigns/" in src["exclude"] and p.is_relative_to(dest / "campaigns"): | |
| continue | |
| if p.is_file() and meta not in p.parents: | |
| st = p.stat() | |
| local[str(p.relative_to(dest))] = (st.st_size, int(st.st_mtime)) | |
| todo = [p for p, (size, mtime) in local.items() | |
| if cache.get(p, [None, None])[:2] != [size, mtime]] | |
| print(f"[{src['name']}] hashing {len(todo)} new/changed files", flush=True) | |
| mismatches = [] | |
| remote_hashes = {} | |
| for i in range(0, len(todo), 500): | |
| remote_hashes.update(sha_remote(src, [p for p in todo[i:i + 500] if p in inv])) | |
| for p in todo: | |
| digest = sha_local(dest / p) | |
| if p in inv and remote_hashes.get(p) != digest: | |
| mismatches.append(p) | |
| continue | |
| cache[p] = [*local[p], digest] | |
| cache = {p: v for p, v in cache.items() if p in local} | |
| cache_path.write_text(json.dumps(cache, sort_keys=True)) | |
| (meta / "SHA256SUMS").write_text("".join(f"{cache[p][2]} {p}\n" for p in sorted(cache))) | |
| rows = ["path\tsize\tremote_mtime\tstatus"] | |
| for p in sorted(set(inv) | set(local)): | |
| if p == "CENTRE_MIRROR.md": | |
| status = "local_note" | |
| elif p not in inv: | |
| status = "local_only(removed_on_remote_or_excluded)" | |
| elif p in local: | |
| status = "local" | |
| else: | |
| status = "remote_only(hdf5_not_eligible)" if p.endswith(".hdf5") else "remote_only" | |
| size, mtime = inv.get(p, local.get(p)) | |
| rows.append(f"{p}\t{size}\t{mtime}\t{status}") | |
| (meta / "REMOTE_INVENTORY.tsv").write_text("\n".join(rows) + "\n") | |
| if (dest / "runs").is_dir(): | |
| summarize_runs(dest, meta) | |
| heads = {} | |
| for repo in ("code", "code_v2"): | |
| if (dest / repo / ".git").exists(): | |
| heads[repo] = subprocess.run( | |
| ["git", "-C", str(dest / repo), "log", "-1", "--format=%H %cI %s"], | |
| capture_output=True, text=True).stdout.strip() | |
| remote_only = [p for p in inv if p not in local] | |
| record = { | |
| "source": src["name"], "remote": f"{HOST}:{src['remote']}", "dest": src["dest"], | |
| "started_at": started, "finished_at": datetime.now(timezone.utc).isoformat(), | |
| "remote_files": len(inv), "remote_bytes": sum(s for s, _ in inv.values()), | |
| "local_files": len(local), "local_bytes": sum(s for s, _ in local.values()), | |
| "hdf5_copied": len(hdf5), | |
| "remote_only_files": len(remote_only), | |
| "remote_only_bytes": sum(inv[p][0] for p in remote_only), | |
| "newly_verified": len(todo) - len(mismatches), "sha256_mismatches": mismatches, | |
| "git_heads": heads, | |
| } | |
| (meta / "LAST_SYNC.json").write_text(json.dumps(record, indent=2, ensure_ascii=False) + "\n") | |
| with open(ROOT / "sync" / "SYNC_LOG.jsonl", "a") as f: | |
| f.write(json.dumps(record, ensure_ascii=False) + "\n") | |
| print(json.dumps(record, indent=2, ensure_ascii=False), flush=True) | |
| if mismatches: | |
| sys.exit(f"SHA-256 mismatch for {len(mismatches)} files; see LAST_SYNC.json") | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--dry-run", action="store_true") | |
| ap.add_argument("--source", action="append", help="sync only this source name") | |
| ap.add_argument("--summary-only", action="store_true", | |
| help="only rebuild _sync/RUNS_SUMMARY.tsv from local files") | |
| args = ap.parse_args() | |
| for src in SOURCES: | |
| if not args.source or src["name"] in args.source: | |
| if args.summary_only: | |
| dest = ROOT / src["dest"] | |
| if (dest / "runs").is_dir(): | |
| summarize_runs(dest, dest / "_sync") | |
| else: | |
| sync(src, args.dry_run) | |