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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import time
|
| 8 |
+
from dataclasses import asdict, dataclass
|
| 9 |
+
from datetime import datetime, timezone
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Iterable
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def iso_now() -> str:
|
| 15 |
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass(frozen=True)
|
| 19 |
+
class TrainerIdentity:
|
| 20 |
+
pid: int
|
| 21 |
+
start_ticks: int
|
| 22 |
+
cmdline: str
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def read_cmdline(proc_dir: Path) -> list[str]:
|
| 26 |
+
try:
|
| 27 |
+
return [
|
| 28 |
+
part.decode("utf-8", errors="replace")
|
| 29 |
+
for part in (proc_dir / "cmdline").read_bytes().split(b"\0")
|
| 30 |
+
if part
|
| 31 |
+
]
|
| 32 |
+
except Exception:
|
| 33 |
+
return []
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def read_start_ticks(proc_dir: Path) -> int | None:
|
| 37 |
+
try:
|
| 38 |
+
stat = (proc_dir / "stat").read_text(encoding="utf-8", errors="replace")
|
| 39 |
+
rest = stat[stat.rfind(")") + 2 :].split()
|
| 40 |
+
return int(rest[19])
|
| 41 |
+
except Exception:
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def find_trainers(script_name: str, required_arg: str) -> list[TrainerIdentity]:
|
| 46 |
+
matches: list[TrainerIdentity] = []
|
| 47 |
+
for proc_dir in Path("/proc").iterdir():
|
| 48 |
+
if not proc_dir.name.isdigit():
|
| 49 |
+
continue
|
| 50 |
+
args = read_cmdline(proc_dir)
|
| 51 |
+
if not args or required_arg not in args:
|
| 52 |
+
continue
|
| 53 |
+
if not any(Path(arg).name == script_name for arg in args):
|
| 54 |
+
continue
|
| 55 |
+
start_ticks = read_start_ticks(proc_dir)
|
| 56 |
+
if start_ticks is None:
|
| 57 |
+
continue
|
| 58 |
+
matches.append(TrainerIdentity(int(proc_dir.name), start_ticks, " ".join(args)))
|
| 59 |
+
return sorted(matches, key=lambda item: item.pid)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def path_artifacts(path: Path) -> list[Path]:
|
| 63 |
+
return [
|
| 64 |
+
path,
|
| 65 |
+
path.with_suffix(".sha256"),
|
| 66 |
+
path.with_suffix(path.suffix + ".upload.sha256"),
|
| 67 |
+
path.with_suffix(path.suffix + ".dtmp"),
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def delete_artifacts(path: Path) -> list[str]:
|
| 72 |
+
deleted: list[str] = []
|
| 73 |
+
for artifact in path_artifacts(path):
|
| 74 |
+
try:
|
| 75 |
+
if artifact.exists():
|
| 76 |
+
artifact.unlink()
|
| 77 |
+
deleted.append(str(artifact))
|
| 78 |
+
except Exception as exc:
|
| 79 |
+
deleted.append(f"FAILED {artifact}: {type(exc).__name__}: {exc}")
|
| 80 |
+
return deleted
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def matching_checkpoints(save_dir: Path, pattern: str, excluded_name_parts: Iterable[str]) -> list[Path]:
|
| 84 |
+
excluded = tuple(excluded_name_parts)
|
| 85 |
+
return sorted(
|
| 86 |
+
[
|
| 87 |
+
path
|
| 88 |
+
for path in save_dir.glob(pattern)
|
| 89 |
+
if path.is_file()
|
| 90 |
+
and path.stat().st_size > 0
|
| 91 |
+
and not any(part in path.name for part in excluded)
|
| 92 |
+
],
|
| 93 |
+
key=lambda path: path.stat().st_mtime,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def prune_to_keep(
|
| 98 |
+
save_dir: Path,
|
| 99 |
+
pattern: str,
|
| 100 |
+
keep: int,
|
| 101 |
+
excluded_name_parts: Iterable[str] = (),
|
| 102 |
+
) -> list[str]:
|
| 103 |
+
if keep < 0:
|
| 104 |
+
return []
|
| 105 |
+
checkpoints = matching_checkpoints(save_dir, pattern, excluded_name_parts)
|
| 106 |
+
victims = checkpoints[: max(0, len(checkpoints) - keep)]
|
| 107 |
+
deleted: list[str] = []
|
| 108 |
+
for victim in victims:
|
| 109 |
+
deleted.extend(delete_artifacts(victim))
|
| 110 |
+
return deleted
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def prune_stale_tmp(save_dir: Path, older_than_sec: int) -> list[str]:
|
| 114 |
+
if older_than_sec <= 0:
|
| 115 |
+
return []
|
| 116 |
+
cutoff = time.time() - older_than_sec
|
| 117 |
+
deleted: list[str] = []
|
| 118 |
+
for tmp in save_dir.glob("*.dtmp"):
|
| 119 |
+
try:
|
| 120 |
+
if tmp.is_file() and tmp.stat().st_mtime < cutoff:
|
| 121 |
+
tmp.unlink()
|
| 122 |
+
deleted.append(str(tmp))
|
| 123 |
+
except Exception as exc:
|
| 124 |
+
deleted.append(f"FAILED {tmp}: {type(exc).__name__}: {exc}")
|
| 125 |
+
return deleted
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def prune_orphan_sidecars(save_dir: Path) -> list[str]:
|
| 129 |
+
deleted: list[str] = []
|
| 130 |
+
sidecars = sorted(set(save_dir.glob("*.sha256")) | set(save_dir.glob("*.pt.upload.sha256")))
|
| 131 |
+
for sidecar in sidecars:
|
| 132 |
+
name = sidecar.name
|
| 133 |
+
if name.endswith(".pt.upload.sha256"):
|
| 134 |
+
base = save_dir / name[: -len(".upload.sha256")]
|
| 135 |
+
elif name.endswith(".sha256"):
|
| 136 |
+
base = save_dir / name[: -len(".sha256")]
|
| 137 |
+
else:
|
| 138 |
+
continue
|
| 139 |
+
try:
|
| 140 |
+
if not base.exists():
|
| 141 |
+
sidecar.unlink()
|
| 142 |
+
deleted.append(str(sidecar))
|
| 143 |
+
except Exception as exc:
|
| 144 |
+
deleted.append(f"FAILED {sidecar}: {type(exc).__name__}: {exc}")
|
| 145 |
+
return deleted
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def free_gb(path: Path) -> float:
|
| 149 |
+
stat = os.statvfs(path)
|
| 150 |
+
return (stat.f_bavail * stat.f_frsize) / (1024**3)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def prune_uploaded_delta_for_reserve(save_dir: Path, reserve_free_gb: float) -> list[str]:
|
| 154 |
+
if reserve_free_gb <= 0 or free_gb(save_dir) >= reserve_free_gb:
|
| 155 |
+
return []
|
| 156 |
+
deltas = matching_checkpoints(save_dir, "*_delta_step*.pt", ())
|
| 157 |
+
deleted: list[str] = []
|
| 158 |
+
for delta in deltas:
|
| 159 |
+
upload_marker = delta.with_suffix(delta.suffix + ".upload.sha256")
|
| 160 |
+
if not upload_marker.exists():
|
| 161 |
+
continue
|
| 162 |
+
deleted.extend(delete_artifacts(delta))
|
| 163 |
+
if free_gb(save_dir) >= reserve_free_gb:
|
| 164 |
+
break
|
| 165 |
+
return deleted
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def write_state(path: Path, payload: dict) -> None:
|
| 169 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 170 |
+
path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def same_trainer(current: list[TrainerIdentity], initial: TrainerIdentity) -> bool:
|
| 174 |
+
return any(item.pid == initial.pid and item.start_ticks == initial.start_ticks for item in current)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def run_once(args: argparse.Namespace, initial: TrainerIdentity) -> dict:
|
| 178 |
+
current = find_trainers(args.script_name, args.required_arg)
|
| 179 |
+
if not same_trainer(current, initial):
|
| 180 |
+
return {
|
| 181 |
+
"checked_at": iso_now(),
|
| 182 |
+
"action": "exit_training_restarted",
|
| 183 |
+
"initial_trainer": asdict(initial),
|
| 184 |
+
"current_trainers": [asdict(item) for item in current],
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
deleted = {
|
| 188 |
+
"delta": prune_to_keep(args.save_dir, "*_delta_step*.pt", args.keep_delta),
|
| 189 |
+
"full": prune_to_keep(args.save_dir, "*_step*.pt", args.keep_full, ("_delta_step",)),
|
| 190 |
+
"uploaded_delta_for_reserve": prune_uploaded_delta_for_reserve(args.save_dir, args.reserve_free_gb),
|
| 191 |
+
"orphan_sidecars": prune_orphan_sidecars(args.save_dir),
|
| 192 |
+
"stale_tmp": prune_stale_tmp(args.save_dir, args.stale_tmp_sec),
|
| 193 |
+
}
|
| 194 |
+
state = {
|
| 195 |
+
"checked_at": iso_now(),
|
| 196 |
+
"action": "pruned",
|
| 197 |
+
"save_dir": str(args.save_dir),
|
| 198 |
+
"free_gb": round(free_gb(args.save_dir), 3),
|
| 199 |
+
"initial_trainer": asdict(initial),
|
| 200 |
+
"deleted": deleted,
|
| 201 |
+
"policy": {
|
| 202 |
+
"keep_delta": args.keep_delta,
|
| 203 |
+
"keep_full": args.keep_full,
|
| 204 |
+
"interval_sec": args.interval_sec,
|
| 205 |
+
"reserve_free_gb": args.reserve_free_gb,
|
| 206 |
+
"stale_tmp_sec": args.stale_tmp_sec,
|
| 207 |
+
"stop_on_training_restart": True,
|
| 208 |
+
},
|
| 209 |
+
}
|
| 210 |
+
return state
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def main() -> int:
|
| 214 |
+
parser = argparse.ArgumentParser(description="Local AGILLM4 checkpoint pruning guard")
|
| 215 |
+
parser.add_argument("--save-dir", type=Path, default=Path(os.environ.get("AGILLM4_SAVE_DIR", "/workspace/agillm4_4090_ckpts")))
|
| 216 |
+
parser.add_argument("--state", type=Path, default=Path(os.environ.get("AGILLM4_PRUNE_STATE", "/workspace/agillm4_local_prune_guard_state.json")))
|
| 217 |
+
parser.add_argument("--script-name", default=os.environ.get("AGILLM4_TRAIN_SCRIPT_NAME", "nB300_agillm4.py"))
|
| 218 |
+
parser.add_argument("--required-arg", default=os.environ.get("AGILLM4_TRAIN_REQUIRED_ARG", "train"))
|
| 219 |
+
parser.add_argument("--keep-delta", type=int, default=int(os.environ.get("AGILLM4_LOCAL_KEEP_DELTA", "1")))
|
| 220 |
+
parser.add_argument("--keep-full", type=int, default=int(os.environ.get("AGILLM4_LOCAL_KEEP_FULL", "1")))
|
| 221 |
+
parser.add_argument("--interval-sec", type=int, default=int(os.environ.get("AGILLM4_PRUNE_INTERVAL_SEC", "300")))
|
| 222 |
+
parser.add_argument("--reserve-free-gb", type=float, default=float(os.environ.get("AGILLM4_PRUNE_RESERVE_GB", "6")))
|
| 223 |
+
parser.add_argument("--stale-tmp-sec", type=int, default=int(os.environ.get("AGILLM4_PRUNE_STALE_TMP_SEC", "3600")))
|
| 224 |
+
parser.add_argument("--once", action="store_true")
|
| 225 |
+
args = parser.parse_args()
|
| 226 |
+
|
| 227 |
+
trainers = find_trainers(args.script_name, args.required_arg)
|
| 228 |
+
if len(trainers) != 1:
|
| 229 |
+
state = {
|
| 230 |
+
"checked_at": iso_now(),
|
| 231 |
+
"action": "exit_bad_trainer_count",
|
| 232 |
+
"trainer_count": len(trainers),
|
| 233 |
+
"trainers": [asdict(item) for item in trainers],
|
| 234 |
+
}
|
| 235 |
+
write_state(args.state, state)
|
| 236 |
+
print(json.dumps(state, indent=2, sort_keys=True), flush=True)
|
| 237 |
+
return 2
|
| 238 |
+
|
| 239 |
+
initial = trainers[0]
|
| 240 |
+
print(f"[prune-guard] guarding trainer pid={initial.pid} start_ticks={initial.start_ticks}", flush=True)
|
| 241 |
+
while True:
|
| 242 |
+
state = run_once(args, initial)
|
| 243 |
+
write_state(args.state, state)
|
| 244 |
+
print(json.dumps(state, indent=2, sort_keys=True), flush=True)
|
| 245 |
+
if state["action"].startswith("exit_"):
|
| 246 |
+
return 0
|
| 247 |
+
if args.once:
|
| 248 |
+
return 0
|
| 249 |
+
time.sleep(max(5, args.interval_sec))
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
raise SystemExit(main())
|