ensemble-pipeline / scripts /hf_sync.py
MikeGreen2710's picture
Add files using upload-large-folder tool
db219d2 verified
Raw
History Blame Contribute Delete
18.1 kB
#!/usr/bin/env python3
"""
hf_sync.py — Sync project to/from a HuggingFace dataset repository.
BOOTSTRAP (brand new VM, no scripts yet):
# Option A — wget this script directly from HuggingFace raw:
wget https://huggingface.co/datasets/your-org/your-project/resolve/main/scripts/hf_sync.py
python hf_sync.py pull --profile full
# Option B — use huggingface-cli, no script needed at all:
pip install huggingface_hub
huggingface-cli download your-org/your-project --repo-type dataset --local-dir .
PUSH (upload changes):
python scripts/hf_sync.py push
python scripts/hf_sync.py push --message "added kl_v2"
PULL PROFILES:
# Everything
python scripts/hf_sync.py pull --profile full
# Inference on one task only (deployment + its model weights)
python scripts/hf_sync.py pull --profile inference --task dist_to_main_street
# Train a new task from scratch (scripts + configs + data, no weights)
python scripts/hf_sync.py pull --profile core
WHAT EACH PROFILE DOWNLOADS:
full — everything except logs
inference — scripts/ + tasks/<task>/experiments/*/deployment/
+ the specific model weight dirs listed in deployment_config.json
+ tasks/<task>/configs/
core — scripts/ + configs/ (all tasks) + data/ (no weights, no experiments)
IGNORED ON PUSH (never uploaded):
*.log, ensemble_log_*.txt training logs
**/__pycache__/, *.pyc Python cache
**/inference_cache*/ inference resume caches (all variants)
**/val_cache/ validation-harness cache
**/_token_cache/ MLM pretraining token arrows
.git/, .hf_config.json local-only files
"""
import argparse
import json
import os
import re
import sys
import time
from pathlib import Path
HF_CONFIG_FILE = ".hf_config.json"
DEFAULT_PUSH_IGNORE = [
"*.log",
"ensemble_log_*.txt",
"**/__pycache__",
"*.pyc",
"*.pyo",
"**/inference_cache*",
"**/.cache",
"**/.ipynb_checkpoints",
"**/val_cache",
"**/_token_cache",
".git",
HF_CONFIG_FILE,
]
# =============================================================================
# PROJECT ROOT DETECTION
# =============================================================================
def get_project_root() -> Path:
"""
Always the parent of the 'scripts' directory containing this file.
Works whether called as 'python scripts/hf_sync.py' or 'python hf_sync.py'.
"""
here = Path(__file__).parent.resolve()
return here.parent if here.name == "scripts" else here
# =============================================================================
# CONFIG
# =============================================================================
def load_config(root: Path) -> dict:
p = root / HF_CONFIG_FILE
return json.load(open(p)) if p.exists() else {}
def save_config(root: Path, cfg: dict):
with open(root / HF_CONFIG_FILE, "w") as f:
json.dump(cfg, f, indent=2)
# =============================================================================
# PUSH
# =============================================================================
def cmd_push(args):
from huggingface_hub import HfApi, create_repo
root = get_project_root()
cfg = load_config(root)
api = HfApi()
repo_id = args.repo or cfg.get("repo_id")
if not repo_id:
print("ERROR: No repo set. Use --repo your-org/repo-name (saved after first use).")
sys.exit(1)
if args.create:
create_repo(repo_id=repo_id, repo_type="dataset",
private=False, exist_ok=True)
print("Repo created (or already exists): {}".format(repo_id))
ignore = list(DEFAULT_PUSH_IGNORE) + (args.exclude or [])
print("\nPushing to https://huggingface.co/datasets/{}".format(repo_id))
print("Local root : {}".format(root))
print("Ignore : {}".format(ignore))
if args.dry_run:
_dry_run_list(root, ignore)
return
t0 = time.perf_counter()
# Use upload_large_folder for repos > ~20GB — it uploads in parallel chunks
# with automatic retry and resumability. Falls back to upload_folder for
# smaller repos where the overhead isn't worth it.
total_mb = sum(f.stat().st_size for f in root.rglob("*") if f.is_file()) / 1e6
if total_mb > 20_000 or args.large:
print("Using upload_large_folder ({:.1f} GB)...".format(total_mb / 1024))
print("Progress is printed per-shard. Safe to Ctrl+C and resume.")
api.upload_large_folder(
folder_path = str(root),
repo_id = repo_id,
repo_type = "dataset",
ignore_patterns = ignore,
)
commit_url = "https://huggingface.co/datasets/{}".format(repo_id)
else:
info = api.upload_folder(
folder_path = str(root),
repo_id = repo_id,
repo_type = "dataset",
ignore_patterns = ignore,
commit_message = args.message or "sync: {}".format(
time.strftime("%Y-%m-%d %H:%M")),
)
commit_url = getattr(info, "commit_url", str(info))
elapsed = time.perf_counter() - t0
print("\nDone in {:.1f}s — {}".format(elapsed, commit_url))
cfg.update({"repo_id": repo_id,
"last_push": time.strftime("%Y-%m-%d %H:%M:%S"),
"last_commit": commit_url})
save_config(root, cfg)
print("Config saved to {}. Future pushes: python scripts/hf_sync.py push".format(
HF_CONFIG_FILE))
def _dry_run_list(root: Path, ignore_patterns: list):
import fnmatch
def _ignored(rel: str) -> bool:
parts = Path(rel).parts
for pat in ignore_patterns:
pat_clean = pat.lstrip("**/").rstrip("/")
if fnmatch.fnmatch(rel, pat):
return True
if any(fnmatch.fnmatch(p, pat_clean) for p in parts):
return True
return False
files = [str(p.relative_to(root)) for p in root.rglob("*") if p.is_file()]
to_up = [f for f in files if not _ignored(f)]
total = sum((root / f).stat().st_size for f in to_up)
print("\n[DRY RUN] {} files, {:.1f} MB".format(len(to_up), total / 1e6))
for f in sorted(to_up)[:60]:
print(" {:>8.1f} MB {}".format((root / f).stat().st_size / 1e6, f))
if len(to_up) > 60:
print(" ... and {} more".format(len(to_up) - 60))
# =============================================================================
# PULL — profile resolution
# =============================================================================
def _allow_patterns_for_profile(profile: str, task: str,
root: Path, repo_id: str) -> list | None:
"""
Return an allow-list of glob patterns for snapshot_download.
None means download everything (full profile).
Profile: full | core | inference
"""
if profile == "full":
return None # no filter — download everything
if profile == "core":
# Scripts + all task configs + data. No experiment artifacts or weights.
return [
"scripts/**",
"configs/**",
"data/**",
"tasks/*/configs/**",
".gitignore",
"README.md",
]
if profile == "inference":
if not task:
print("ERROR: --task is required for --profile inference")
sys.exit(1)
# Base: scripts + this task's configs + deployment artifacts
patterns = [
"scripts/**",
"tasks/{}/configs/**".format(task),
"tasks/{}/experiments/**/deployment/**".format(task),
"tasks/{}/experiments/**/embeddings/**".format(task),
]
# Read deployment_config.json from the local copy if it exists,
# otherwise we can't know which model weights are needed yet —
# in that case include all experiment artifacts for this task.
dep_cfg = _find_deployment_config(root, task)
if dep_cfg:
weight_patterns = _weight_patterns_from_config(dep_cfg, task)
patterns.extend(weight_patterns)
print(" Deployment config found — downloading {} model weight pattern(s).".format(
len(weight_patterns)))
else:
# No local config yet — download full task experiments
print(" No local deployment_config.json found for task '{}'.".format(task))
print(" Downloading all experiment artifacts for this task.")
patterns.append("tasks/{}/experiments/**".format(task))
return patterns
print("ERROR: Unknown profile '{}'. Use full / core / inference.".format(profile))
sys.exit(1)
def _find_deployment_config(root: Path, task: str) -> dict | None:
"""
Look for deployment_config.json under tasks/<task>/experiments/*/deployment/.
Returns the first one found, or None.
"""
task_dir = root / "tasks" / task / "experiments"
if not task_dir.exists():
# Also check legacy flat structure: experiments/<task>/
task_dir = root / "experiments"
for p in task_dir.rglob("deployment_config.json"):
try:
return json.load(open(p))
except Exception:
pass
return None
def _weight_patterns_from_config(dep_cfg: dict, task: str) -> list:
"""
Extract HuggingFace glob patterns for the model weight directories
referenced in a deployment_config.json.
We match by clean_name inside the known artifacts directory structure.
Each model needs: pretrained_checkpoints__<safe_name>/ (all folds).
"""
patterns = []
for m in dep_cfg.get("models", []):
art_dir = m.get("artifacts_dir", "")
mname = m.get("model_name", "")
split_unk = m.get("split_unknown_stage", False)
# Derive the safe artifact directory name used on disk
if split_unk:
for stage in ["stage1", "stage2"]:
safe = (mname + "__" + stage).replace("/", "__")
# Match relative to project root — strip absolute prefix
pat = _make_relative_glob(art_dir, safe, task)
if pat:
patterns.append(pat)
else:
safe = mname.replace("/", "__")
pat = _make_relative_glob(art_dir, safe, task)
if pat:
patterns.append(pat)
return patterns
def _make_relative_glob(art_dir: str, safe_model_name: str, task: str) -> str | None:
"""
Convert an absolute artifacts_dir + safe model name into a glob pattern
relative to the project root.
Examples:
/home/user/tasks/dist_to_main_street/experiments/ce_v1/artifacts
+ pretrained_checkpoints__MikeGreen2710__mlm_listing__stage1
-> tasks/dist_to_main_street/experiments/ce_v1/artifacts/pretrained_checkpoints__MikeGreen2710__mlm_listing__stage1/**
Falls back to a task-scoped glob if the absolute path can't be parsed.
"""
if not art_dir:
return None
art_path = Path(art_dir)
# Try to find 'tasks' or 'experiments' anchor in the path parts
parts = art_path.parts
for anchor in ("tasks", "experiments"):
if anchor in parts:
idx = list(parts).index(anchor)
rel_dir = Path(*parts[idx:])
return str(rel_dir / safe_model_name) + "/**"
# Fallback: just use task-scoped wildcard
return "tasks/{}/**/{}/{safe}/**".format(task, safe_model_name)
# =============================================================================
# PULL COMMAND
# =============================================================================
def cmd_pull(args):
from huggingface_hub import snapshot_download
root = Path(args.dest).resolve() if args.dest else get_project_root()
cfg = load_config(root)
repo_id = args.repo or cfg.get("repo_id")
if not repo_id:
print("ERROR: No repo specified. Use --repo your-org/repo-name")
print("\nBootstrap from scratch:")
print(" pip install huggingface_hub && huggingface-cli login")
print(" huggingface-cli download your-org/repo --repo-type dataset --local-dir .")
sys.exit(1)
profile = args.profile
task = args.task
patterns = _allow_patterns_for_profile(profile, task, root, repo_id)
print("Pulling from https://huggingface.co/datasets/{}".format(repo_id))
print("Profile : {}".format(profile) +
(" (task={})".format(task) if task else ""))
print("Destination : {}".format(root))
if patterns is not None:
print("Patterns : {} allow pattern(s)".format(len(patterns)))
for p in patterns:
print(" {}".format(p))
else:
print("Patterns : all files")
if not args.yes:
confirm = input("\nContinue? [y/N] ").strip().lower()
if confirm != "y":
print("Aborted.")
return
root.mkdir(parents=True, exist_ok=True)
t0 = time.perf_counter()
local_dir = snapshot_download(
repo_id = repo_id,
repo_type = "dataset",
local_dir = str(root),
allow_patterns = patterns,
ignore_patterns = [HF_CONFIG_FILE],
)
elapsed = time.perf_counter() - t0
print("\nDownloaded in {:.1f}s -> {}".format(elapsed, local_dir))
cfg.update({"repo_id": repo_id,
"last_pull": time.strftime("%Y-%m-%d %H:%M:%S"),
"last_pull_profile": profile})
save_config(root, cfg)
# Print next-step hints
print("\nNext steps:")
if profile == "inference":
print(" python scripts/meta_learner_inference.py \\")
print(" --config tasks/{}/experiments/.../deployment/deployment_config.json \\".format(
task or "<task>"))
print(" --data_path data/<new_data>.parquet \\")
print(" --text_col text --output_path data/predictions.parquet --device cuda")
elif profile == "core":
print(" # Train a new task:")
print(" python scripts/ensemble_distillation_generator.py \\")
print(" --ensemble_config_path tasks/<new_task>/configs/ce_ensemble.json \\")
print(" --artifacts_dir tasks/<new_task>/experiments/ce_v1/artifacts \\")
print(" --data_path data/<labelled_data>.parquet ...")
else:
print(" python scripts/hf_sync.py push # to sync changes back")
# =============================================================================
# STATUS
# =============================================================================
def cmd_status(args):
root = get_project_root()
cfg = load_config(root)
if not cfg:
print("No HF config. Run: python scripts/hf_sync.py push --repo your-org/repo --create")
return
print("HuggingFace Sync Status")
print(" Project root : {}".format(root))
print(" Repo : {}".format(cfg.get("repo_id", "not set")))
print(" Last push : {}".format(cfg.get("last_push", "never")))
print(" Last pull : {}".format(cfg.get("last_pull", "never")))
if cfg.get("repo_id"):
print(" URL : https://huggingface.co/datasets/{}".format(cfg["repo_id"]))
# =============================================================================
# PARSE ARGS
# =============================================================================
def parse_args():
p = argparse.ArgumentParser(
description="Sync project to/from HuggingFace dataset repo.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
sub = p.add_subparsers(dest="command", required=True)
# push
push = sub.add_parser("push", help="Upload changed files to HuggingFace.")
push.add_argument("--repo", type=str, default=None)
push.add_argument("--create", action="store_true",
help="Create the repo if it doesn't exist.")
push.add_argument("--public", action="store_true",
help="Make the repo public (default: private).")
push.add_argument("--message", type=str, default=None,
help="Commit message.")
push.add_argument("--exclude", type=str, nargs="*", default=[],
help="Extra glob patterns to exclude.")
push.add_argument("--dry_run", action="store_true",
help="Print what would be uploaded without uploading.")
push.add_argument("--large", action="store_true",
help="Force upload_large_folder even for small repos. "
"Auto-selected for repos > 20GB.")
# pull
pull = sub.add_parser("pull", help="Download from HuggingFace.")
pull.add_argument("--repo", type=str, default=None)
pull.add_argument("--dest", type=str, default=None,
help="Destination directory (default: project root).")
pull.add_argument("--profile", type=str, default="full",
choices=["full", "core", "inference"],
help="What to download: full / core / inference.")
pull.add_argument("--task", type=str, default=None,
help="Task name for --profile inference, "
"e.g. dist_to_main_street.")
pull.add_argument("--yes", action="store_true",
help="Skip confirmation.")
# status
sub.add_parser("status", help="Show sync status.")
return p.parse_args()
# =============================================================================
# MAIN
# =============================================================================
def main():
args = parse_args()
try:
import huggingface_hub # noqa
except ImportError:
print("ERROR: pip install huggingface_hub")
sys.exit(1)
{"push": cmd_push, "pull": cmd_pull, "status": cmd_status}[args.command](args)
if __name__ == "__main__":
main()