memoryai's picture
Upload folder using huggingface_hub
b373569 verified
raw
history blame
7.83 kB
"""
Auto-backup system: sync checkpoints, data, and configs to HuggingFace Hub.
Supports resume training from any new VPS.
Setup:
1. huggingface-cli login
2. python3 backup.py --init (tạo repos trên HF)
3. python3 backup.py --backup (push lên HF)
4. python3 backup.py --restore (pull về VPS mới)
"""
import argparse
import subprocess
import time
import threading
from pathlib import Path
from huggingface_hub import HfApi, create_repo, snapshot_download, upload_folder, upload_file
PROJECT_DIR = Path("/home/adminuser/chungcat")
HF_ORG = None # Set to your HF username or org
REPOS = {
"checkpoints": "{user}/4k-image-model-checkpoints",
"data_meta": "{user}/4k-image-model-data",
"scripts": "{user}/4k-image-model-scripts",
}
BACKUP_PATHS = {
"checkpoints": [
PROJECT_DIR / "checkpoints",
],
"data_meta": [
PROJECT_DIR / "data" / "raw" / "coyo_filtered",
PROJECT_DIR / "configs",
],
"scripts": [
PROJECT_DIR / "scripts",
PROJECT_DIR / "configs",
PROJECT_DIR / "PLAN.md",
],
}
def get_hf_user():
api = HfApi()
info = api.whoami()
return info["name"]
def init_repos(user):
"""Create HF repos if they don't exist."""
api = HfApi()
for key, repo_template in REPOS.items():
repo_id = repo_template.format(user=user)
try:
create_repo(repo_id, repo_type="model" if key == "checkpoints" else "dataset", exist_ok=True)
print(f" Repo ready: {repo_id}")
except Exception as e:
print(f" Error creating {repo_id}: {e}")
def backup_checkpoints(user):
"""Upload latest checkpoint to HF."""
api = HfApi()
repo_id = REPOS["checkpoints"].format(user=user)
ckpt_dir = PROJECT_DIR / "checkpoints"
if not ckpt_dir.exists():
print(" No checkpoints to backup")
return
# Find all checkpoint dirs
for model_dir in ckpt_dir.iterdir():
if not model_dir.is_dir():
continue
# Upload latest checkpoint only (save bandwidth)
checkpoints = sorted(model_dir.glob("checkpoint-*"), key=lambda p: int(p.name.split("-")[1]) if p.name.split("-")[1].isdigit() else 0)
final = model_dir / "final"
to_upload = None
if final.exists():
to_upload = final
elif checkpoints:
to_upload = checkpoints[-1]
if to_upload:
path_in_repo = f"{model_dir.name}/{to_upload.name}"
print(f" Uploading {to_upload}{repo_id}/{path_in_repo}")
upload_folder(
folder_path=str(to_upload),
repo_id=repo_id,
path_in_repo=path_in_repo,
repo_type="model",
)
def backup_data_meta(user):
"""Upload filtered parquets and configs."""
api = HfApi()
repo_id = REPOS["data_meta"].format(user=user)
for path in BACKUP_PATHS["data_meta"]:
if not path.exists():
continue
rel_path = path.relative_to(PROJECT_DIR)
print(f" Uploading {rel_path}{repo_id}")
upload_folder(
folder_path=str(path),
repo_id=repo_id,
path_in_repo=str(rel_path),
repo_type="dataset",
)
def backup_scripts(user):
"""Upload all scripts and configs."""
api = HfApi()
repo_id = REPOS["scripts"].format(user=user)
for path in BACKUP_PATHS["scripts"]:
if not path.exists():
continue
rel_path = path.relative_to(PROJECT_DIR)
if path.is_file():
print(f" Uploading {rel_path}")
upload_file(
path_or_fileobj=str(path),
repo_id=repo_id,
path_in_repo=str(rel_path),
repo_type="dataset",
)
else:
print(f" Uploading {rel_path}/")
upload_folder(
folder_path=str(path),
repo_id=repo_id,
path_in_repo=str(rel_path),
repo_type="dataset",
)
def backup_all(user):
"""Full backup."""
print("\n=== Backing up scripts ===")
backup_scripts(user)
print("\n=== Backing up data metadata ===")
backup_data_meta(user)
print("\n=== Backing up checkpoints ===")
backup_checkpoints(user)
print("\n=== Backup complete! ===")
def restore(user):
"""Restore everything from HF to a new VPS."""
print("\n=== Restoring from HuggingFace ===")
# Restore scripts
repo_id = REPOS["scripts"].format(user=user)
print(f"\n Restoring scripts from {repo_id}...")
try:
snapshot_download(
repo_id=repo_id,
repo_type="dataset",
local_dir=str(PROJECT_DIR),
)
except Exception as e:
print(f" Warning: {e}")
# Restore data metadata
repo_id = REPOS["data_meta"].format(user=user)
print(f"\n Restoring data metadata from {repo_id}...")
try:
snapshot_download(
repo_id=repo_id,
repo_type="dataset",
local_dir=str(PROJECT_DIR),
)
except Exception as e:
print(f" Warning: {e}")
# Restore checkpoints
repo_id = REPOS["checkpoints"].format(user=user)
print(f"\n Restoring checkpoints from {repo_id}...")
try:
snapshot_download(
repo_id=repo_id,
repo_type="model",
local_dir=str(PROJECT_DIR / "checkpoints"),
)
except Exception as e:
print(f" Warning: {e}")
print("\n=== Restore complete! ===")
class AutoBackup:
"""Background thread that backs up every N minutes."""
def __init__(self, user, interval_minutes=30):
self.user = user
self.interval = interval_minutes * 60
self.running = False
self.thread = None
def start(self):
self.running = True
self.thread = threading.Thread(target=self._loop, daemon=True)
self.thread.start()
print(f"Auto-backup started (every {self.interval // 60} minutes)")
def stop(self):
self.running = False
if self.thread:
self.thread.join()
def _loop(self):
while self.running:
time.sleep(self.interval)
if not self.running:
break
try:
print(f"\n[Auto-backup] Starting backup at {time.strftime('%H:%M:%S')}...")
backup_all(self.user)
print(f"[Auto-backup] Done at {time.strftime('%H:%M:%S')}")
except Exception as e:
print(f"[Auto-backup] Error: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Backup/restore to HuggingFace Hub")
parser.add_argument("--init", action="store_true", help="Create HF repos")
parser.add_argument("--backup", action="store_true", help="Backup to HF")
parser.add_argument("--restore", action="store_true", help="Restore from HF")
parser.add_argument("--auto", action="store_true", help="Start auto-backup daemon")
parser.add_argument("--interval", type=int, default=30, help="Auto-backup interval (minutes)")
parser.add_argument("--user", default=None, help="HF username (auto-detected if logged in)")
args = parser.parse_args()
user = args.user or get_hf_user()
print(f"HuggingFace user: {user}")
if args.init:
print("\nInitializing repos...")
init_repos(user)
elif args.backup:
backup_all(user)
elif args.restore:
restore(user)
elif args.auto:
ab = AutoBackup(user, args.interval)
ab.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
ab.stop()
else:
print("Specify --init, --backup, --restore, or --auto")