File size: 18,147 Bytes
b66e8d3 | 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 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | #!/usr/bin/env python3
"""Live training status for the ICML geometric-memory Claim 1 run.
Usage:
# one-shot pretty print
python repro/scripts/training_status.py
# continuous terminal watch (Ctrl+C to stop viewer only)
python repro/scripts/training_status.py --watch --interval 5
# also rewrite the Claim 1 logbook cell + status files
python repro/scripts/training_status.py --logbook
# background-friendly: watch + logbook updates
python repro/scripts/training_status.py --watch --interval 30 --logbook
"""
from __future__ import annotations
import argparse
import json
import os
import re
import signal
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
# Prefer active symlink, then newest claim1 log.
def _default_log() -> Path:
active = ROOT / "logs_claim1_active.log"
if active.exists():
return active.resolve() if active.is_symlink() else active
candidates = sorted(
ROOT.glob("logs_claim1*.log"),
key=lambda p: p.stat().st_mtime if p.exists() else 0,
reverse=True,
)
return candidates[0] if candidates else ROOT / "logs_claim1_medium.log"
DEFAULT_LOG = _default_log()
STATUS_JSON = ROOT / "repro" / "outputs" / "training_status.json"
STATUS_MD = ROOT / "repro" / "outputs" / "training_status.md"
STATUS_HTML = ROOT / "repro" / "outputs" / "training_status.html"
CLAIM1_PAGE = (
ROOT
/ ".trackio"
/ "logbook"
/ "pages"
/ "claim-1-path-star-near-perfect-accuracy"
/ "page.md"
)
LIVE_BEGIN = "<!-- LIVE-TRAINING-STATUS-BEGIN -->"
LIVE_END = "<!-- LIVE-TRAINING-STATUS-END -->"
TRAIN_CMDS = (
"train_in_weights.py",
"geometry_and_spectral_repro.py",
)
def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
def find_training_processes() -> list[dict]:
"""Return running training-related python processes."""
try:
out = subprocess.check_output(
["ps", "-eo", "pid,etime,pcpu,pmem,args"],
text=True,
stderr=subprocess.DEVNULL,
)
except Exception:
return []
procs = []
for line in out.splitlines()[1:]:
if not any(cmd in line for cmd in TRAIN_CMDS):
continue
if "training_status.py" in line:
continue
parts = line.strip().split(None, 4)
if len(parts) < 5:
continue
pid, etime, pcpu, pmem, args = parts
procs.append(
{
"pid": int(pid),
"etime": etime,
"pcpu": pcpu,
"pmem": pmem,
"cmd": args[:200],
}
)
return procs
def gpu_snapshot() -> dict | None:
try:
out = subprocess.check_output(
[
"nvidia-smi",
"--query-gpu=name,utilization.gpu,memory.used,memory.total",
"--format=csv,noheader,nounits",
],
text=True,
stderr=subprocess.DEVNULL,
)
name, util, used, total = [x.strip() for x in out.strip().splitlines()[0].split(",")]
return {
"name": name,
"util_pct": float(util),
"mem_used_mib": float(used),
"mem_total_mib": float(total),
}
except Exception:
return None
def _last_match(pattern: str, text: str):
ms = list(re.finditer(pattern, text))
return ms[-1] if ms else None
def parse_log(log_path: Path) -> dict:
status: dict = {
"log_path": str(log_path),
"log_exists": log_path.exists(),
"log_bytes": log_path.stat().st_size if log_path.exists() else 0,
"log_mtime": (
datetime.fromtimestamp(log_path.stat().st_mtime, tz=timezone.utc).isoformat()
if log_path.exists()
else None
),
"stage": "unknown",
"finished": False,
"edge": None,
"path": None,
"last_test_acc": None,
"best_test_acc": None,
"forced_acc": None,
"run_dir": None,
"model_params": None,
"device": None,
"graph": None,
"recent_lines": [],
}
if not log_path.exists():
return status
# For large tqdm logs, only need the tail for most metrics, but epoch regexes
# are densest at the end. Read last ~400KB + full scan for rare markers.
raw = log_path.read_bytes()
tail = raw[-400_000:].decode("utf-8", errors="ignore")
head = raw[:20_000].decode("utf-8", errors="ignore")
text = tail if len(raw) > 400_000 else raw.decode("utf-8", errors="ignore")
m = re.search(r"Device: (\S+)", head + "\n" + text)
if m:
status["device"] = m.group(1)
m = re.search(r"Graph setup: ([^\n]+)", head + "\n" + text)
if m:
status["graph"] = m.group(1).strip()
m = re.search(r"Model parameters: ([0-9,]+)", head + "\n" + text)
if m:
status["model_params"] = m.group(1)
m = re.search(r"Run directory: ([^\n]+)", head + "\n" + text)
if m:
status["run_dir"] = m.group(1).strip()
if "Training finished" in text or "Final checkpoint saved" in text:
status["finished"] = True
status["stage"] = "finished"
m = _last_match(
r"Edge Epoch (\d+)/(\d+):\s*.*?acc=([0-9.]+)%,\s*loss=([0-9.]+)",
text,
)
if m:
status["edge"] = {
"epoch": int(m.group(1)),
"total": int(m.group(2)),
"acc_pct": float(m.group(3)),
"loss": float(m.group(4)),
"frac": int(m.group(1)) / max(int(m.group(2)), 1),
}
if not status["finished"]:
status["stage"] = "edge_memorization"
m = _last_match(
r"Path Epoch (\d+)/(\d+):\s*.*?acc=([0-9.]+)%,\s*loss=([0-9.]+)",
text,
)
if m:
status["path"] = {
"epoch": int(m.group(1)),
"total": int(m.group(2)),
"acc_pct": float(m.group(3)),
"loss": float(m.group(4)),
"frac": int(m.group(1)) / max(int(m.group(2)), 1),
}
if not status["finished"]:
status["stage"] = "path_finetuning"
# mixed_full_path recipe logs "Joint Epoch"
m = _last_match(
r"Joint Epoch (\d+)/(\d+):\s*.*?acc=([0-9.]+)%,\s*loss=([0-9.]+)",
text,
)
if m:
status["path"] = {
"epoch": int(m.group(1)),
"total": int(m.group(2)),
"acc_pct": float(m.group(3)),
"loss": float(m.group(4)),
"frac": int(m.group(1)) / max(int(m.group(2)), 1),
"kind": "joint_mixed",
}
if not status["finished"]:
status["stage"] = "joint_mixed_training"
m = _last_match(r"Epoch (\d+) \| Test Acc: ([0-9.]+)%", text)
if m:
status["last_test_acc"] = {"epoch": int(m.group(1)), "acc_pct": float(m.group(2))}
m = _last_match(r"Forced Acc: ([0-9.]+)", text)
if m:
try:
status["forced_acc"] = float(m.group(1))
except ValueError:
pass
m = _last_match(r"Best test accuracy:\s*([0-9.]+)%", text)
if m:
status["best_test_acc"] = float(m.group(1))
if "Starting path" in text or "PATH FINETUNING" in text.upper() or "Path finetuning" in text:
if status["stage"] == "edge_memorization" and status.get("path"):
status["stage"] = "path_finetuning"
elif status["stage"] == "unknown" and not status["finished"]:
status["stage"] = "path_finetuning"
if "EDGE MEMORIZATION TRAINING" in text and status["stage"] == "unknown":
status["stage"] = "edge_memorization"
# clean recent non-tqdm-ish lines from absolute end
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
interesting = [
ln
for ln in lines
if any(
k in ln
for k in (
"Edge Epoch",
"Path Epoch",
"Test Acc",
"Best test",
"Final checkpoint",
"Training finished",
"INFO",
"ERROR",
)
)
]
status["recent_lines"] = interesting[-8:]
return status
def progress_bar(frac: float, width: int = 28) -> str:
frac = max(0.0, min(1.0, frac))
filled = int(round(frac * width))
return "[" + "#" * filled + "-" * (width - filled) + f"] {frac*100:5.1f}%"
def build_snapshot(log_path: Path) -> dict:
procs = find_training_processes()
log_status = parse_log(log_path)
snap = {
"updated_at": _now(),
"running": bool(procs) and not log_status.get("finished"),
"processes": procs,
"gpu": gpu_snapshot(),
"log": log_status,
}
return snap
def format_text(snap: dict) -> str:
log = snap["log"]
lines = []
lines.append("=" * 60)
lines.append("ICML Repro — Claim 1 training status")
lines.append(f"Updated: {snap['updated_at']}")
lines.append("=" * 60)
if snap["processes"]:
for p in snap["processes"]:
lines.append(
f"PID {p['pid']} elapsed={p['etime']} cpu={p['pcpu']}% "
f"mem={p['pmem']}% running"
)
lines.append(f" {p['cmd']}")
else:
lines.append("No train_in_weights.py process found.")
if snap.get("gpu"):
g = snap["gpu"]
lines.append(
f"GPU: {g['name']} util={g['util_pct']:.0f}% "
f"mem={g['mem_used_mib']:.0f}/{g['mem_total_mib']:.0f} MiB"
)
lines.append(f"Stage: {log.get('stage')}")
lines.append(f"Finished: {log.get('finished')}")
if log.get("graph"):
lines.append(f"Graph: {log['graph']}")
if log.get("model_params"):
lines.append(f"Params: {log['model_params']}")
if log.get("device"):
lines.append(f"Device: {log['device']}")
if log.get("edge"):
e = log["edge"]
lines.append(
f"Edge: epoch {e['epoch']}/{e['total']} "
f"acc={e['acc_pct']:.2f}% loss={e['loss']:.4f}"
)
lines.append(" " + progress_bar(e["frac"]))
if log.get("path"):
p = log["path"]
lines.append(
f"Path: epoch {p['epoch']}/{p['total']} "
f"acc={p['acc_pct']:.2f}% loss={p['loss']:.4f}"
)
lines.append(" " + progress_bar(p["frac"]))
if log.get("last_test_acc") is not None:
t = log["last_test_acc"]
lines.append(f"Last test acc: {t['acc_pct']:.2f}% (epoch {t['epoch']})")
if log.get("best_test_acc") is not None:
lines.append(f"Best test acc: {log['best_test_acc']:.2f}%")
lines.append(f"Log: {log.get('log_path')} ({log.get('log_bytes', 0)} bytes)")
if log.get("run_dir"):
lines.append(f"Run dir: {log['run_dir']}")
lines.append("-" * 60)
lines.append("Tip: tail -f logs_claim1_medium.log")
lines.append(" python repro/scripts/training_status.py --watch")
lines.append("Logbook UI: http://localhost:7861/")
lines.append("=" * 60)
return "\n".join(lines)
def format_markdown(snap: dict) -> str:
log = snap["log"]
running = "🟢 **running**" if snap["running"] else (
"✅ **finished**" if log.get("finished") else "⚪ **idle / unknown**"
)
parts = [
f"### Live training status",
f"_Auto-updated: {snap['updated_at']}_ · {running}",
"",
]
if snap["processes"]:
p = snap["processes"][0]
parts.append(f"- **PID:** `{p['pid']}` · elapsed `{p['etime']}` · CPU `{p['pcpu']}%`")
if snap.get("gpu"):
g = snap["gpu"]
parts.append(
f"- **GPU:** {g['name']} · util `{g['util_pct']:.0f}%` · "
f"mem `{g['mem_used_mib']:.0f}/{g['mem_total_mib']:.0f}` MiB"
)
parts.append(f"- **Stage:** `{log.get('stage')}`")
if log.get("edge"):
e = log["edge"]
parts.append(
f"- **Edge memorization:** epoch **{e['epoch']}/{e['total']}** · "
f"acc **{e['acc_pct']:.2f}%** · loss `{e['loss']:.4f}` \n"
f" `{progress_bar(e['frac'])}`"
)
if log.get("path"):
p = log["path"]
parts.append(
f"- **Path finetuning:** epoch **{p['epoch']}/{p['total']}** · "
f"acc **{p['acc_pct']:.2f}%** · loss `{p['loss']:.4f}` \n"
f" `{progress_bar(p['frac'])}`"
)
if log.get("last_test_acc"):
t = log["last_test_acc"]
parts.append(f"- **Last held-out test acc:** **{t['acc_pct']:.2f}%** (epoch {t['epoch']})")
if log.get("best_test_acc") is not None:
parts.append(f"- **Best test acc:** **{log['best_test_acc']:.2f}%**")
if log.get("graph"):
parts.append(f"- **Graph:** `{log['graph']}`")
parts.append(f"- **Log file:** `logs_claim1_medium.log`")
parts.append("")
parts.append(
"Watch in terminal: `python repro/scripts/training_status.py --watch` · "
"or `tail -f logs_claim1_medium.log`"
)
return "\n".join(parts)
def format_html(snap: dict) -> str:
mdish = format_markdown(snap).replace("\n", "<br>\n")
# simple HTML, auto-refresh every 10s if opened in browser
return f"""<!doctype html>
<html><head>
<meta charset="utf-8"/>
<meta http-equiv="refresh" content="10"/>
<title>Claim 1 training status</title>
<style>
body {{ font-family: ui-sans-serif, system-ui, sans-serif; margin: 1.5rem; max-width: 720px; }}
code {{ background: #f4f4f5; padding: 0.1rem 0.3rem; border-radius: 4px; }}
.box {{ border: 1px solid #e4e4e7; border-radius: 12px; padding: 1rem 1.25rem; }}
h1 {{ font-size: 1.25rem; }}
</style>
</head>
<body>
<h1>Claim 1 — training status</h1>
<p>Auto-refreshes every 10s. Generated {_now()}.</p>
<div class="box">{mdish}</div>
<p><a href="http://localhost:7861/">Open Trackio logbook</a></p>
</body></html>
"""
def write_status_files(snap: dict) -> None:
STATUS_JSON.parent.mkdir(parents=True, exist_ok=True)
STATUS_JSON.write_text(json.dumps(snap, indent=2))
STATUS_MD.write_text(format_markdown(snap) + "\n")
STATUS_HTML.write_text(format_html(snap))
def update_logbook_page(snap: dict) -> bool:
"""Rewrite the live-status block inside the Claim 1 page markdown."""
if not CLAIM1_PAGE.exists():
return False
body = format_markdown(snap)
block = f"{LIVE_BEGIN}\n\n{body}\n\n{LIVE_END}"
text = CLAIM1_PAGE.read_text(encoding="utf-8")
if LIVE_BEGIN in text and LIVE_END in text:
pre, rest = text.split(LIVE_BEGIN, 1)
_, post = rest.split(LIVE_END, 1)
new_text = pre + block + post
else:
# Insert a trackio-style markdown cell near the top (after title)
cell = (
"\n\n---\n"
"<!-- trackio-cell\n"
'{"type": "markdown", "id": "cell_live_training_status", '
f'"created_at": "{datetime.now(timezone.utc).isoformat()}", '
'"title": "Live training status"}\n'
"-->\n"
f"{block}\n"
)
# after first heading block
if "\n\n" in text:
head, tail = text.split("\n\n", 1)
new_text = head + "\n\n" + cell + "\n" + tail
else:
new_text = text + cell
CLAIM1_PAGE.write_text(new_text, encoding="utf-8")
# bump logbook.json updated_at so the UI notices
lb = ROOT / ".trackio" / "logbook" / "logbook.json"
if lb.exists():
try:
data = json.loads(lb.read_text())
data["updated_at"] = datetime.now(timezone.utc).isoformat()
lb.write_text(json.dumps(data, indent=2))
except Exception:
pass
return True
def once(log_path: Path, logbook: bool, quiet: bool = False) -> dict:
snap = build_snapshot(log_path)
write_status_files(snap)
if logbook:
update_logbook_page(snap)
if not quiet:
print(format_text(snap))
print(f"\nWrote {STATUS_JSON.relative_to(ROOT)}")
print(f"Wrote {STATUS_MD.relative_to(ROOT)}")
print(f"Wrote {STATUS_HTML.relative_to(ROOT)} (open in browser; auto-refresh 10s)")
if logbook:
print(f"Updated logbook page: {CLAIM1_PAGE.relative_to(ROOT)}")
print("Refresh http://localhost:7861/ → Claim 1")
return snap
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--log", type=Path, default=DEFAULT_LOG, help="Training log path")
parser.add_argument("--watch", action="store_true", help="Refresh continuously")
parser.add_argument("--interval", type=float, default=5.0, help="Watch interval seconds")
parser.add_argument(
"--logbook",
action="store_true",
help="Rewrite live status block on Claim 1 logbook page",
)
parser.add_argument(
"--json",
action="store_true",
help="Print JSON snapshot only",
)
args = parser.parse_args(argv)
stop = False
def _sig(_s, _f):
nonlocal stop
stop = True
signal.signal(signal.SIGINT, _sig)
signal.signal(signal.SIGTERM, _sig)
if args.watch:
while not stop:
# clear screen for readable watch
if not args.json and sys.stdout.isatty():
os.system("clear" if os.name != "nt" else "cls")
snap = once(args.log, logbook=args.logbook, quiet=args.json)
if args.json:
print(json.dumps(snap, indent=2))
if snap["log"].get("finished") and not snap["running"]:
if not args.json:
print("\nTraining finished — exiting watch.")
break
# sleep in small chunks so Ctrl+C is snappy
end = time.time() + args.interval
while time.time() < end and not stop:
time.sleep(0.2)
return 0
snap = once(args.log, logbook=args.logbook, quiet=args.json)
if args.json:
print(json.dumps(snap, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|