Download PROJECT/tools/make_restore.py from Dhruv1000/TSRDA: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/Dhruv1000/TSRDA/resolve/main/PROJECT/tools/make_restore.py
- Command line
-
hf download hf://Dhruv1000/TSRDA/PROJECT/tools/make_restore.py
-
curl -L -o make_restore.py https://huggingface.co/Dhruv1000/TSRDA/resolve/main/PROJECT/tools/make_restore.py
15.2 kB
| """Build and publish a complete, self-contained RESTORE kit for Dhruv1000/TSRDA. | |
| Goal: if the VM is lost, a fresh VM can be brought back to this exact working state from the | |
| Hub repository alone (plus re-downloading the two public datasets). | |
| What it produces (staged under hf_work/stage4/ and uploaded): | |
| CLAUDE.md project brief + rules + chat-request log (read by Claude Code) | |
| RESTORE/code_snapshot.tar.gz every code/script/config/log/result-json under ~/pro, minus data, | |
| weights and third-party clones (see MANIFEST.json) | |
| RESTORE/MANIFEST.json sha256 of every file in the snapshot + every file left out | |
| RESTORE/third_party.json url + exact commit of each cloned baseline repo | |
| RESTORE/requirements.freeze.txt, ENVIRONMENT.txt | |
| RESTORE/RESTORE.md, restore.sh the step-by-step guide and its executable form | |
| HISTORY/ CHAT_LOG.md, CONTEXT_SUMMARIES.md, raw/*.jsonl.gz (secrets removed) | |
| MEMORY/ the assistant's persistent memory files | |
| and uploads the model weights that were not in the repo yet (all MTLCC / PLANTEUR pre-training | |
| checkpoints, the in-flight fine-tune state, the external TESSERA student). | |
| Needs HF_TOKEN in the environment; the token is never written anywhere. | |
| python3 make_restore.py build # stage only | |
| python3 make_restore.py push # build + upload | |
| """ | |
| import os, sys, re, io, json, gzip, shutil, hashlib, tarfile, subprocess, datetime | |
| from pathlib import Path | |
| os.environ["HF_HUB_DISABLE_XET"] = "1" # must precede the huggingface_hub import | |
| os.environ.setdefault("HF_HOME", "/home/ubuntu/pro/hf_work/hfhome") | |
| os.environ.setdefault("HF_XET_CACHE", "/home/ubuntu/pro/hf_work/hfhome/xet") | |
| HOME = Path("/home/ubuntu") | |
| PRO = HOME / "pro" | |
| HF = PRO / "hf_work" | |
| S4 = HF / "stage4" | |
| REPO = "Dhruv1000/TSRDA" | |
| NOW = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC") | |
| # ----------------------------------------------------------------------------- what goes in the snapshot | |
| ROOTS = ["TSRDA_MTLCC", "TSRDA_PLANTEUR", "TSRDA_FOUNDATION", "baselines", "PAPER", "hf_work", "planteur_meta"] | |
| SKIP_DIRS = {"__pycache__", ".git", "hfhome", "stage2", "stage3", "stage4", "stage", "dl", "hf_home", "repos", | |
| "training_features", "checkpoints", ".ipynb_checkpoints", "external", "tmp"} | |
| SKIP_EXT = {".tar", ".pt", ".pth", ".ckpt", ".npy", ".npz", ".whl", ".zip", ".safetensors", ".bin", | |
| ".pyc", ".h5", ".parquet", ".tif", ".tiff"} | |
| KEEP_BIG = {"zip_entries.pkl"} # index of the 42 GB Zenodo zip: saves a long re-scan | |
| MAX_BYTES = 8_000_000 | |
| SECRET = re.compile(r"hf_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{30,}|" | |
| r"-----BEGIN [A-Z ]*PRIVATE KEY-----") | |
| def sh(cmd, **kw): | |
| return subprocess.run(cmd, shell=True, capture_output=True, text=True, **kw).stdout.strip() | |
| def sha(p, blk=1 << 20): | |
| h = hashlib.sha256() | |
| with open(p, "rb") as f: | |
| while b := f.read(blk): | |
| h.update(b) | |
| return h.hexdigest() | |
| # ----------------------------------------------------------------------------- snapshot | |
| def build_snapshot(): | |
| out = S4 / "RESTORE" | |
| out.mkdir(parents=True, exist_ok=True) | |
| kept, left = [], [] | |
| for root in ROOTS: | |
| base = PRO / root | |
| if not base.exists(): | |
| continue | |
| for dp, dns, fns in os.walk(base): | |
| dns[:] = sorted(d for d in dns if d not in SKIP_DIRS) | |
| for fn in sorted(fns): | |
| p = Path(dp) / fn | |
| if p.is_symlink() or not p.is_file(): | |
| continue | |
| rel = p.relative_to(PRO).as_posix() | |
| sz = p.stat().st_size | |
| if p.suffix.lower() in SKIP_EXT or (sz > MAX_BYTES and fn not in KEEP_BIG): | |
| left.append({"path": rel, "bytes": sz, "why": "weights / data / large — see RESTORE.md"}) | |
| continue | |
| kept.append((p, rel, sz)) | |
| # never ship a secret: scan every text member before it is written | |
| bad = [] | |
| for p, rel, sz in kept: | |
| if sz < 3_000_000 and p.suffix not in (".pkl", ".gz", ".pdf", ".png", ".jpg"): | |
| try: | |
| if SECRET.search(p.read_text(errors="ignore")): | |
| bad.append(rel) | |
| except Exception: | |
| pass | |
| assert not bad, f"secret-shaped strings found in: {bad[:5]}" | |
| tgz = out / "code_snapshot.tar.gz" | |
| man = [] | |
| with tarfile.open(tgz, "w:gz", compresslevel=6) as tf: | |
| for p, rel, sz in kept: | |
| tf.add(p, arcname=rel) | |
| man.append({"path": rel, "bytes": sz, "sha256": sha(p)}) | |
| (out / "MANIFEST.json").write_text(json.dumps( | |
| {"built": NOW, "root": str(PRO), "files_in_snapshot": len(man), "files": man, | |
| "left_out": left}, indent=1)) | |
| print(f"snapshot: {len(man)} files kept, {len(left)} left out, {tgz.stat().st_size/1e6:.1f} MB") | |
| return left | |
| # ----------------------------------------------------------------------------- environment + third party | |
| def build_env(): | |
| out = S4 / "RESTORE" | |
| (out / "requirements.freeze.txt").write_text(sh("python3 -m pip freeze 2>/dev/null") + "\n") | |
| env = [f"built {NOW}", f"python {sh('python3 --version')}", | |
| f"os {sh('lsb_release -ds 2>/dev/null || uname -a')}", | |
| f"kernel {sh('uname -r')}", | |
| "gpu " + sh("nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv,noheader"), | |
| "cuda(torch) " + sh("python3 -c 'import torch;print(torch.__version__, torch.version.cuda)'"), | |
| f"tectonic {sh('~/.local/bin/tectonic --version 2>/dev/null')}", | |
| f"disk {sh('df -h / | tail -1')}"] | |
| (out / "ENVIRONMENT.txt").write_text("\n".join(env) + "\n") | |
| repos = {} | |
| for d in sorted((PRO / "baselines/repos").glob("*")): | |
| if (d / ".git").exists(): | |
| repos[f"baselines/repos/{d.name}"] = { | |
| "url": sh(f"git -C {d} remote get-url origin"), | |
| "commit": sh(f"git -C {d} rev-parse HEAD"), | |
| "modified_files": sh(f"git -C {d} status --porcelain | grep -v __pycache__ | wc -l")} | |
| for name in ("STCLN", "TSRDA"): | |
| d = PRO / name | |
| if (d / ".git").exists(): | |
| repos[name] = {"url": sh(f"git -C {d} remote get-url origin"), | |
| "commit": sh(f"git -C {d} rev-parse HEAD"), | |
| "modified_files": sh(f"git -C {d} status --porcelain | wc -l")} | |
| (out / "third_party.json").write_text(json.dumps(repos, indent=1)) | |
| # ----------------------------------------------------------------------------- history / memory / claude.md | |
| def build_history(): | |
| sys.path.insert(0, str(HF)) | |
| import make_history | |
| make_history.main(S4 / "HISTORY") | |
| # the three "session continued" summaries are the densest record of decisions: keep them whole | |
| chat = (S4 / "HISTORY/raw") | |
| parts = ["# Context summaries written at each compaction\n", | |
| "Each block is the summary Claude Code produced when the context filled up. Together they are the " | |
| "most compact account of what was decided and why. Secrets are removed.\n"] | |
| for g in sorted(chat.glob("360de0a1*.gz")): | |
| n = 0 | |
| for line in gzip.open(g, "rt"): | |
| try: | |
| d = json.loads(line) | |
| except Exception: | |
| continue | |
| if d.get("type") != "user": | |
| continue | |
| c = d.get("message", {}).get("content") | |
| txt = c if isinstance(c, str) else " ".join(b.get("text", "") for b in (c or []) if isinstance(b, dict)) | |
| if txt.lstrip().startswith("This session is being continued"): | |
| n += 1 | |
| ts = (d.get("timestamp") or "")[:16].replace("T", " ") | |
| parts.append(f"\n---\n\n## Compaction {n} · {ts} UTC\n\n{txt.strip()}\n") | |
| (S4 / "HISTORY/CONTEXT_SUMMARIES.md").write_text("".join(parts)) | |
| mem = S4 / "MEMORY" | |
| mem.mkdir(exist_ok=True) | |
| for f in (HOME / ".claude/projects/-home-ubuntu-pro/memory").glob("*.md"): | |
| shutil.copy(f, mem / f.name) | |
| def request_log(): | |
| """The user's genuine requests, in order, taken straight from the transcript.""" | |
| rows = [] | |
| for g in sorted((S4 / "HISTORY/raw").glob("360de0a1*.gz")): | |
| for line in gzip.open(g, "rt"): | |
| try: | |
| d = json.loads(line) | |
| except Exception: | |
| continue | |
| if d.get("type") != "user": | |
| continue | |
| c = d.get("message", {}).get("content") | |
| txt = c if isinstance(c, str) else " ".join(b.get("text", "") for b in (c or []) | |
| if isinstance(b, dict) and b.get("type") == "text") | |
| txt = re.sub(r"<system-reminder>.*?</system-reminder>", "", txt, flags=re.S).strip() | |
| if (not txt or txt.startswith(("<", "[SYSTEM", "This session is being", "Base directory", | |
| "[Request interrupted")) or "tool_use_id" in txt[:50]): | |
| continue | |
| ts = (d.get("timestamp") or "")[:16].replace("T", " ") | |
| rows.append(f"| {ts} | " + " ".join(txt.split())[:260].replace("|", "/") + " |") | |
| return rows | |
| def build_claude_md(left): | |
| tpl = (HF / "claude_md_template.md").read_text() | |
| reqs = "\n".join(["| UTC | request (first 260 chars) |", "|---|---|"] + request_log()) | |
| big = sorted(left, key=lambda x: -x["bytes"])[:0] | |
| (S4 / "CLAUDE.md").write_text(tpl.replace("{{BUILT}}", NOW).replace("{{REQUEST_LOG}}", reqs)) | |
| # ----------------------------------------------------------------------------- upload | |
| CKPT = [ # (local folder, remote folder, glob) | |
| (PRO / "TSRDA_MTLCC/runs/checkpoints/pretrain", "MTLCC/checkpoints/pretrain_mask015", "*.tar"), | |
| (PRO / "TSRDA_MTLCC/runs_mask04/checkpoints/pretrain", "MTLCC/checkpoints/pretrain_mask04_inprogress", "*.tar"), | |
| (PRO / "TSRDA_MTLCC/runs_mask04/finetune_mask04", "MTLCC/checkpoints/mask04_finetune", "model_best*.tar"), | |
| (PRO / "TSRDA_PLANTEUR/runs/checkpoints/pretrain", "PLANTEUR/checkpoints/pretrain_all", "*.tar"), | |
| (PRO / "TSRDA_MTLCC/external/tessera/ckpt", "MTLCC/external/tessera", "*.pt"), | |
| ] | |
| def push(): | |
| from huggingface_hub import HfApi | |
| sys.path.insert(0, str(HF)) | |
| import hf_layout | |
| api = hf_layout.patch(HfApi(token=os.environ["HF_TOKEN"])) # historical paths -> simple public layout | |
| stamp = f"({NOW})" | |
| for loc, rem, pat in CKPT: | |
| files = sorted(loc.glob(pat)) | |
| if not files: | |
| continue | |
| api.upload_folder(folder_path=str(loc), path_in_repo=rem, repo_id=REPO, allow_patterns=[pat], | |
| commit_message=f"Checkpoints: {rem} ({len(files)} files) {stamp}") | |
| print("uploaded", rem, len(files), "files") | |
| # --- everything else needed to resume that is not in the code snapshot ------------------------------------- | |
| M, FDN = PRO / "TSRDA_MTLCC", PRO / "TSRDA_FOUNDATION" | |
| for n in ("refinement", "sam", "structured_ft"): # MTLCC branch networks: EMA weights (raw were uploaded earlier) | |
| f = M / f"runs/{n}/model_best_ema.tar" | |
| if f.exists(): | |
| api.upload_file(path_or_fileobj=str(f), path_in_repo=f"MTLCC/checkpoints/option2_{n}_best_ema.tar", repo_id=REPO, | |
| commit_message=f"MTLCC {n} EMA weights {stamp}") | |
| for n in ("original", "optical"): # cached training features used by the MTLCC readouts | |
| f = M / f"runs/training_features/{n}.npy" | |
| if f.exists(): | |
| api.upload_file(path_or_fileobj=str(f), path_in_repo=f"MTLCC/enhancement/cache/{n}.npy", repo_id=REPO, | |
| commit_message=f"MTLCC cached training features {n} {stamp}") | |
| for src, dst in ((M / "tools/zip_entries.pkl", "MTLCC/tools/zip_entries.pkl"), | |
| (PRO / "baselines/logs/resource_log.csv", "BASELINES/logs/resource_log.csv")): | |
| if src.exists(): | |
| api.upload_file(path_or_fileobj=str(src), path_in_repo=dst, repo_id=REPO, commit_message=f"{dst} {stamp}") | |
| st = PRO / "STCLN" # the authors' code + released pre-trained weights (STCLN_wp) | |
| if st.exists(): | |
| api.upload_folder(folder_path=str(st), path_in_repo="BASELINES/third_party/STCLN", repo_id=REPO, | |
| ignore_patterns=[".git/*", "**/.git/*", "__pycache__/*", "**/__pycache__/*"], | |
| commit_message=f"STCLN code and released weights {stamp}") | |
| snap = Path("/dev/shm/repos_snapshot.tar.gz") # unmodified copies of the eight baseline repos (no .git) | |
| try: | |
| subprocess.run(["tar", "--exclude=.git", "-czf", str(snap), "-C", str(PRO / "baselines"), "repos"], check=True) | |
| api.upload_file(path_or_fileobj=str(snap), path_in_repo="BASELINES/third_party/repos_snapshot.tar.gz", repo_id=REPO, | |
| commit_message=f"Baseline repo sources, in case upstream disappears {stamp}") | |
| finally: | |
| snap.unlink(missing_ok=True) | |
| # in-flight fine-tune state, so an interrupted PLANTEUR run can resume | |
| for d in sorted((PRO / "TSRDA_PLANTEUR/runs/finetune").glob("*")): | |
| if not (d / "result.json").exists() and (d / "latest.tar").exists(): | |
| api.upload_file(path_or_fileobj=str(d / "latest.tar"), repo_id=REPO, | |
| path_in_repo=f"PLANTEUR/checkpoints/in_progress/{d.name}/latest.tar", | |
| commit_message=f"In-progress fine-tune state {d.name} {stamp}") | |
| print("uploaded in-progress", d.name) | |
| # baseline weights + results (hash-deduplicated by the Hub, so only new files move) | |
| api.upload_folder(folder_path=str(PRO / "baselines/results"), path_in_repo="BASELINES/results", repo_id=REPO, | |
| commit_message=f"Baseline results and weights {stamp}") | |
| # the kit itself | |
| api.upload_file(path_or_fileobj=str(S4 / "CLAUDE.md"), path_in_repo="CLAUDE.md", repo_id=REPO, | |
| commit_message=f"CLAUDE.md: project brief, rules, request log {stamp}") | |
| for sub in ("RESTORE", "HISTORY", "MEMORY"): | |
| api.upload_folder(folder_path=str(S4 / sub), path_in_repo=sub, repo_id=REPO, | |
| commit_message=f"{sub}: restore kit {stamp}") | |
| print("uploaded", sub) | |
| for f in ("make_history.py", "make_restore.py", "claude_md_template.md", "make_figures.py", "readme_builder.py"): | |
| api.upload_file(path_or_fileobj=str(HF / f), path_in_repo=f"TOOLS/{f}", repo_id=REPO, | |
| commit_message=f"Tools: {f} {stamp}") | |
| def main(): | |
| mode = sys.argv[1] if len(sys.argv) > 1 else "build" | |
| if S4.exists(): | |
| shutil.rmtree(S4) | |
| S4.mkdir(parents=True) | |
| left = build_snapshot() | |
| build_env() | |
| build_history() | |
| shutil.copy(HF / "restore.sh", S4 / "RESTORE/restore.sh") | |
| shutil.copy(HF / "RESTORE.md", S4 / "RESTORE/RESTORE.md") | |
| build_claude_md(left) | |
| if mode == "push": | |
| push() | |
| print("done", mode) | |
| if __name__ == "__main__": | |
| main() | |