rotating-cube-cfd / code /upload_hf.py
aloeme's picture
Upload code/upload_hf.py with huggingface_hub
1dcfaca verified
Raw
History Blame Contribute Delete
4.18 kB
#!/usr/bin/env python
"""Split-and-upload the rotating-cube archives to the HF (Xet-backed, public) repo.
The 55 GB monolithic tar.zst files never complete their final Xet commit over this VM's
flaky uplink (chunks transfer for hours but the file never lands), while small files commit
fine. So each archive is split into ~4 GB parts uploaded individually: every part commits
durably in a few minutes, a stall costs at most one part, and restarts skip already-
committed parts (no 55 GB re-scan). Downstream reassembles with `cat`. Xet still dedups at
the chunk level across parts. Runs under upload_watchdog.sh in tmux (disconnect-safe).
"""
import os, glob, time, shutil, subprocess
os.environ.pop("HF_HUB_DISABLE_XET", None) # repo is Xet-backed; must use Xet
os.environ.pop("HF_XET_HIGH_PERFORMANCE", None) # default concurrency (high-perf hangs)
from huggingface_hub import HfApi
ROOT = "/home/aloeme/openfoam"
REPO = "aloeme/rotating-cube-cfd"
UP = os.path.join(ROOT, "hf_upload")
PARTS = os.path.join(UP, "parts")
PART_SIZE = os.environ.get("PART_SIZE", "4000M") # ~4 GB parts
SCRIPTS = ["section2d.py", "extrude3d.py", "validate_cube.py", "visualize_sample.py",
"run_sweep.sh", "viz_all.sh", "pack_dataset.sh", "upload_hf.py",
"upload_watchdog.sh"]
token = open(os.path.join(ROOT, "hf_token")).read().strip()
api = HfApi(token=token)
def log(m): print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
def push(local, repo_path, tries=8):
for i in range(tries):
try:
api.upload_file(path_or_fileobj=local, path_in_repo=repo_path,
repo_id=REPO, repo_type="dataset")
return True
except Exception as e:
log(f" retry {i+1}/{tries} {repo_path}: {str(e)[:120]}")
time.sleep(min(90, 10 * (i + 1)))
log(f" GAVE UP {repo_path}")
return False
def committed():
try:
return set(api.list_repo_files(REPO, repo_type="dataset"))
except Exception as e:
log(f"list failed: {e}"); return set()
# 1) reproduction scripts + card (fast no-ops if unchanged)
for s in SCRIPTS + ["DATASET.md", "README_hf.md"]:
p = os.path.join(ROOT, s)
if os.path.exists(p):
push(p, "README.md" if s.startswith("README") else f"code/{s}")
# 2) per case: split into parts (guarded by a marker), upload each part, then drop local parts
archives = sorted(glob.glob(os.path.join(UP, "*.tar.zst")))
log(f"{len(archives)} archives to split+upload as {PART_SIZE} parts")
for arc in archives:
case = os.path.basename(arc)[:-len(".tar.zst")]
if not os.path.exists(arc + ".sha256"):
continue # still being packed
have = committed()
# already fully uploaded? (marker file on the repo written last)
if f"data/{case}/PARTS_COMPLETE" in have:
log(f"SKIP {case} (complete)")
continue
pdir = os.path.join(PARTS, case)
if not os.path.exists(os.path.join(pdir, ".split_done")):
shutil.rmtree(pdir, ignore_errors=True)
os.makedirs(pdir, exist_ok=True)
log(f"splitting {case} into {PART_SIZE} parts")
subprocess.run(["split", "-b", PART_SIZE, "-d", "--suffix-length=3",
arc, os.path.join(pdir, f"{case}.tar.zst.part")], check=True)
open(os.path.join(pdir, ".split_done"), "w").close()
parts = sorted(glob.glob(os.path.join(pdir, f"{case}.tar.zst.part*")))
log(f"{case}: {len(parts)} parts")
for p in parts:
rp = f"data/{case}/{os.path.basename(p)}"
if rp in have:
continue
gb = os.path.getsize(p) / 1e9
log(f" upload {os.path.basename(p)} ({gb:.1f} GB)")
push(p, rp)
# checksum of the full archive (for downstream verify after reassembly) + done marker
push(arc + ".sha256", f"data/{case}/{case}.tar.zst.sha256")
open(os.path.join(pdir, "PARTS_COMPLETE"), "w").close()
push(os.path.join(pdir, "PARTS_COMPLETE"), f"data/{case}/PARTS_COMPLETE")
shutil.rmtree(pdir, ignore_errors=True) # reclaim disk
log(f"DONE {case}")
log(f"all cases uploaded -> https://huggingface.co/datasets/{REPO}")