"""Upload training ckpts from local NFS dirs to HF dataset `AE-W/ckpt`, then delete the local copy to free disk. Keeps ``last.ckpt`` local so SLURM preemption can still resume. One sweeper process per node, runs every SWEEP_INTERVAL seconds. Safe to run alongside live training — a ckpt is only swept if its mtime is older than SKIP_MTIME_SECONDS (avoids racing Lightning's writer). Upload layout on HF: AE-W/ckpt (dataset) ├── audioldm_bg2fg_rebalance/.ckpt ├── audioldm_bg2fg_controlnet_rebalance/.ckpt ├── sa_open_bg2fg_rebalance//.ckpt └── frieren_bg2fg_rebalance/.ckpt """ from __future__ import annotations import os import sys import time import traceback from pathlib import Path from typing import Iterable from huggingface_hub import HfApi, create_repo from huggingface_hub.utils import HfHubHTTPError HF_REPO = "AE-W/ckpt" HF_REPO_TYPE = "dataset" SWEEP_INTERVAL = 60 # seconds between scans SKIP_MTIME_SECONDS = 90 # skip files modified in the last N seconds (avoid writer race) KEEP_LOCAL_NAMES = {"last.ckpt"} # never delete the resume anchor DELETE_AFTER_UPLOAD = True # Model key → root checkpoint directory. Globs supported via Path.glob. WATCH: dict[str, list[str]] = { "audioldm_bg2fg_rebalance": [ "/nfs/turbo/coe-ahowens-nobackup/dingqy/AudioLDM-training-finetuning/" "log/latent_diffusion/2023_08_23_reproduce_audioldm/" "audioldm_bg2fg_rebalance/checkpoints", ], "audioldm_bg2fg_controlnet_rebalance": [ "/nfs/turbo/coe-ahowens-nobackup/dingqy/AudioLDM-training-finetuning/" "log/latent_diffusion/2023_08_23_reproduce_audioldm/" "audioldm_bg2fg_controlnet_rebalance/checkpoints", ], "sa_open_bg2fg_rebalance": [ # SA nests one wandb run_id level; walk into it. "/nfs/turbo/coe-ahowens-nobackup/dingqy/friendly-stable-audio-tools/" "output_rebalance/sa_open_bg2fg_rebalance/*/checkpoints", ], "frieren_bg2fg_rebalance": [ "/nfs/turbo/coe-ahowens-nobackup/dingqy/frieren/frieren_bg2fg_logs/" "bg2fg_rebalance/checkpoints", ], } # v2 (AudioLDM2-large, Diffusers/accelerate) saves a *directory* per step # instead of a single .ckpt — `step_NNNNNNNN/{unet/, optimizer.pt, rng.pt, # meta.json}`. Each save is ~8.4 GB (UNet 2.7 GB + optimizer state 5.7 GB). # Resume anchor is `/last`, a symlink to the most recent step dir # (NOT a fixed name like v1's `last.ckpt`). # # We sweep these by uploading the whole step dir as a folder, then deleting # it locally — all dirs except the one `last` currently points to. WATCH_V2: dict[str, list[str]] = { "audioldm2_bg2fg_rebalance": [ "/nfs/turbo/coe-ahowens-nobackup/dingqy/AudioLDM-training-finetuning/" "log/audioldm2_v2/audioldm2_bg2fg_rebalance", ], "audioldm2_bg2fg_controlnet_rebalance": [ "/nfs/turbo/coe-ahowens-nobackup/dingqy/AudioLDM-training-finetuning/" "log/audioldm2_v2/audioldm2_bg2fg_controlnet_rebalance", ], } def iter_ckpt_dirs(patterns: Iterable[str]) -> list[Path]: """Resolve glob patterns to existing directories.""" out: list[Path] = [] for pat in patterns: if "*" in pat: # Expand glob relative to filesystem root. root = Path(pat.split("*", 1)[0]) if not root.parent.exists(): continue rest = pat[len(str(root)):] # Simple glob via Path.glob try: out.extend(Path(p) for p in Path("/").glob(pat.lstrip("/"))) except Exception: pass else: p = Path(pat) if p.exists(): out.append(p) return [d for d in out if d.is_dir()] def eligible_ckpts(root: Path) -> list[Path]: """Return .ckpt files ready for upload (mtime-stable, not in KEEP list).""" now = time.time() out: list[Path] = [] for ckpt in sorted(root.glob("*.ckpt")): if ckpt.name in KEEP_LOCAL_NAMES: continue if not ckpt.is_file(): continue try: if now - ckpt.stat().st_mtime < SKIP_MTIME_SECONDS: continue except FileNotFoundError: continue out.append(ckpt) return out def upload_one(api: HfApi, local: Path, remote: str) -> bool: try: api.upload_file( path_or_fileobj=str(local), path_in_repo=remote, repo_id=HF_REPO, repo_type=HF_REPO_TYPE, commit_message=f"sweep: {remote}", ) return True except HfHubHTTPError as e: print(f" upload FAILED {remote}: HTTPError {e}", flush=True) except Exception as e: print(f" upload FAILED {remote}: {e}", flush=True) return False def upload_folder_one(api: HfApi, local: Path, remote_prefix: str) -> bool: """Upload a directory tree under remote_prefix (preserves layout).""" try: api.upload_folder( folder_path=str(local), path_in_repo=remote_prefix, repo_id=HF_REPO, repo_type=HF_REPO_TYPE, commit_message=f"sweep: {remote_prefix}", ) return True except HfHubHTTPError as e: print(f" upload FAILED {remote_prefix}: HTTPError {e}", flush=True) except Exception as e: print(f" upload FAILED {remote_prefix}: {e}", flush=True) return False def eligible_step_dirs(root: Path) -> tuple[list[Path], Path | None]: """Return (uploadable step dirs, the dir to keep locally). For v2: scan `/step_*` dirs whose mtime is mtime-stable, exclude the one pointed to by `/last` symlink. The keep-anchor is whatever `last` points to (so a SLURM resume can still find a working ckpt). """ now = time.time() keep: Path | None = None last_link = root / "last" if last_link.is_symlink(): try: keep = (root / last_link.readlink()).resolve() except Exception: keep = None out: list[Path] = [] for d in sorted(root.glob("step_*")): if not d.is_dir(): continue if keep is not None and d.resolve() == keep: continue try: mtime = max(p.stat().st_mtime for p in d.rglob("*") if p.is_file()) except (FileNotFoundError, ValueError): continue if now - mtime < SKIP_MTIME_SECONDS: continue out.append(d) return out, keep def dir_size_bytes(p: Path) -> int: return sum(f.stat().st_size for f in p.rglob("*") if f.is_file()) def main() -> None: token = os.environ.get("HF_TOKEN") or "" if not token: sys.exit("HF_TOKEN unset; `source ~/.hf_token` first") api = HfApi(token=token) try: create_repo(HF_REPO, repo_type=HF_REPO_TYPE, exist_ok=True, token=token) except Exception as e: print(f"create_repo warning: {e}", flush=True) print( f"[sweeper] target: https://huggingface.co/datasets/{HF_REPO} " f"interval={SWEEP_INTERVAL}s skip_mtime<{SKIP_MTIME_SECONDS}s", flush=True, ) while True: t0 = time.time() # v1-style: per-file *.ckpt sweep for model, patterns in WATCH.items(): for root in iter_ckpt_dirs(patterns): for ckpt in eligible_ckpts(root): # SA path has an extra run_id dir we want to preserve. if model == "sa_open_bg2fg_rebalance": run_id = root.parent.name remote = f"{model}/{run_id}/{ckpt.name}" else: remote = f"{model}/{ckpt.name}" size_mb = ckpt.stat().st_size / 1e6 print(f"-> {ckpt} ({size_mb:.1f} MB) -> {remote}", flush=True) if upload_one(api, ckpt, remote) and DELETE_AFTER_UPLOAD: try: ckpt.unlink() print(f" deleted local {ckpt.name}", flush=True) except Exception as e: print(f" delete failed: {e}", flush=True) # v2-style: per-step-dir sweep (Diffusers layout) for model, patterns in WATCH_V2.items(): for root in iter_ckpt_dirs(patterns): step_dirs, keep = eligible_step_dirs(root) if step_dirs: print(f"[v2 {model}] {len(step_dirs)} step dir(s) eligible, " f"keep={keep.name if keep else '(none)'}", flush=True) for d in step_dirs: remote = f"{model}/{d.name}" size_gb = dir_size_bytes(d) / 1e9 print(f"-> {d} ({size_gb:.2f} GB folder) -> {remote}", flush=True) if upload_folder_one(api, d, remote) and DELETE_AFTER_UPLOAD: try: import shutil shutil.rmtree(d) print(f" deleted local {d.name}", flush=True) except Exception as e: print(f" delete failed: {e}", flush=True) elapsed = time.time() - t0 time.sleep(max(1.0, SWEEP_INTERVAL - elapsed)) if __name__ == "__main__": try: main() except KeyboardInterrupt: print("\n[sweeper] interrupted", flush=True) except Exception: traceback.print_exc() sys.exit(1)