File size: 9,556 Bytes
219f052 | 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 | """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>.ckpt
βββ audioldm_bg2fg_controlnet_rebalance/<ckpt>.ckpt
βββ sa_open_bg2fg_rebalance/<run_id>/<ckpt>.ckpt
βββ frieren_bg2fg_rebalance/<ckpt>.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 `<root>/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 `<root>/step_*` dirs whose mtime is mtime-stable, exclude
the one pointed to by `<root>/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)
|