| |
| """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] |
| |
| 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 |
|
|
| |
| |
| 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" |
|
|
| |
| 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" |
|
|
| |
| 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") |
| |
| 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: |
| |
| 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" |
| ) |
| |
| 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") |
|
|
| |
| 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: |
| |
| 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 |
| |
| 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()) |
|
|