File size: 18,094 Bytes
4f2fd46 db219d2 4f2fd46 db219d2 4f2fd46 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | #!/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() |