ThreeSixNine commited on
Commit
b66e8d3
·
verified ·
1 Parent(s): 79cd64d

Upload training_status.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. training_status.py +550 -0
training_status.py ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Live training status for the ICML geometric-memory Claim 1 run.
3
+
4
+ Usage:
5
+ # one-shot pretty print
6
+ python repro/scripts/training_status.py
7
+
8
+ # continuous terminal watch (Ctrl+C to stop viewer only)
9
+ python repro/scripts/training_status.py --watch --interval 5
10
+
11
+ # also rewrite the Claim 1 logbook cell + status files
12
+ python repro/scripts/training_status.py --logbook
13
+
14
+ # background-friendly: watch + logbook updates
15
+ python repro/scripts/training_status.py --watch --interval 30 --logbook
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import re
24
+ import signal
25
+ import subprocess
26
+ import sys
27
+ import time
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+
31
+ ROOT = Path(__file__).resolve().parents[2]
32
+ # Prefer active symlink, then newest claim1 log.
33
+ def _default_log() -> Path:
34
+ active = ROOT / "logs_claim1_active.log"
35
+ if active.exists():
36
+ return active.resolve() if active.is_symlink() else active
37
+ candidates = sorted(
38
+ ROOT.glob("logs_claim1*.log"),
39
+ key=lambda p: p.stat().st_mtime if p.exists() else 0,
40
+ reverse=True,
41
+ )
42
+ return candidates[0] if candidates else ROOT / "logs_claim1_medium.log"
43
+
44
+
45
+ DEFAULT_LOG = _default_log()
46
+ STATUS_JSON = ROOT / "repro" / "outputs" / "training_status.json"
47
+ STATUS_MD = ROOT / "repro" / "outputs" / "training_status.md"
48
+ STATUS_HTML = ROOT / "repro" / "outputs" / "training_status.html"
49
+ CLAIM1_PAGE = (
50
+ ROOT
51
+ / ".trackio"
52
+ / "logbook"
53
+ / "pages"
54
+ / "claim-1-path-star-near-perfect-accuracy"
55
+ / "page.md"
56
+ )
57
+
58
+ LIVE_BEGIN = "<!-- LIVE-TRAINING-STATUS-BEGIN -->"
59
+ LIVE_END = "<!-- LIVE-TRAINING-STATUS-END -->"
60
+
61
+ TRAIN_CMDS = (
62
+ "train_in_weights.py",
63
+ "geometry_and_spectral_repro.py",
64
+ )
65
+
66
+
67
+ def _now() -> str:
68
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
69
+
70
+
71
+ def find_training_processes() -> list[dict]:
72
+ """Return running training-related python processes."""
73
+ try:
74
+ out = subprocess.check_output(
75
+ ["ps", "-eo", "pid,etime,pcpu,pmem,args"],
76
+ text=True,
77
+ stderr=subprocess.DEVNULL,
78
+ )
79
+ except Exception:
80
+ return []
81
+ procs = []
82
+ for line in out.splitlines()[1:]:
83
+ if not any(cmd in line for cmd in TRAIN_CMDS):
84
+ continue
85
+ if "training_status.py" in line:
86
+ continue
87
+ parts = line.strip().split(None, 4)
88
+ if len(parts) < 5:
89
+ continue
90
+ pid, etime, pcpu, pmem, args = parts
91
+ procs.append(
92
+ {
93
+ "pid": int(pid),
94
+ "etime": etime,
95
+ "pcpu": pcpu,
96
+ "pmem": pmem,
97
+ "cmd": args[:200],
98
+ }
99
+ )
100
+ return procs
101
+
102
+
103
+ def gpu_snapshot() -> dict | None:
104
+ try:
105
+ out = subprocess.check_output(
106
+ [
107
+ "nvidia-smi",
108
+ "--query-gpu=name,utilization.gpu,memory.used,memory.total",
109
+ "--format=csv,noheader,nounits",
110
+ ],
111
+ text=True,
112
+ stderr=subprocess.DEVNULL,
113
+ )
114
+ name, util, used, total = [x.strip() for x in out.strip().splitlines()[0].split(",")]
115
+ return {
116
+ "name": name,
117
+ "util_pct": float(util),
118
+ "mem_used_mib": float(used),
119
+ "mem_total_mib": float(total),
120
+ }
121
+ except Exception:
122
+ return None
123
+
124
+
125
+ def _last_match(pattern: str, text: str):
126
+ ms = list(re.finditer(pattern, text))
127
+ return ms[-1] if ms else None
128
+
129
+
130
+ def parse_log(log_path: Path) -> dict:
131
+ status: dict = {
132
+ "log_path": str(log_path),
133
+ "log_exists": log_path.exists(),
134
+ "log_bytes": log_path.stat().st_size if log_path.exists() else 0,
135
+ "log_mtime": (
136
+ datetime.fromtimestamp(log_path.stat().st_mtime, tz=timezone.utc).isoformat()
137
+ if log_path.exists()
138
+ else None
139
+ ),
140
+ "stage": "unknown",
141
+ "finished": False,
142
+ "edge": None,
143
+ "path": None,
144
+ "last_test_acc": None,
145
+ "best_test_acc": None,
146
+ "forced_acc": None,
147
+ "run_dir": None,
148
+ "model_params": None,
149
+ "device": None,
150
+ "graph": None,
151
+ "recent_lines": [],
152
+ }
153
+ if not log_path.exists():
154
+ return status
155
+
156
+ # For large tqdm logs, only need the tail for most metrics, but epoch regexes
157
+ # are densest at the end. Read last ~400KB + full scan for rare markers.
158
+ raw = log_path.read_bytes()
159
+ tail = raw[-400_000:].decode("utf-8", errors="ignore")
160
+ head = raw[:20_000].decode("utf-8", errors="ignore")
161
+ text = tail if len(raw) > 400_000 else raw.decode("utf-8", errors="ignore")
162
+
163
+ m = re.search(r"Device: (\S+)", head + "\n" + text)
164
+ if m:
165
+ status["device"] = m.group(1)
166
+ m = re.search(r"Graph setup: ([^\n]+)", head + "\n" + text)
167
+ if m:
168
+ status["graph"] = m.group(1).strip()
169
+ m = re.search(r"Model parameters: ([0-9,]+)", head + "\n" + text)
170
+ if m:
171
+ status["model_params"] = m.group(1)
172
+ m = re.search(r"Run directory: ([^\n]+)", head + "\n" + text)
173
+ if m:
174
+ status["run_dir"] = m.group(1).strip()
175
+
176
+ if "Training finished" in text or "Final checkpoint saved" in text:
177
+ status["finished"] = True
178
+ status["stage"] = "finished"
179
+
180
+ m = _last_match(
181
+ r"Edge Epoch (\d+)/(\d+):\s*.*?acc=([0-9.]+)%,\s*loss=([0-9.]+)",
182
+ text,
183
+ )
184
+ if m:
185
+ status["edge"] = {
186
+ "epoch": int(m.group(1)),
187
+ "total": int(m.group(2)),
188
+ "acc_pct": float(m.group(3)),
189
+ "loss": float(m.group(4)),
190
+ "frac": int(m.group(1)) / max(int(m.group(2)), 1),
191
+ }
192
+ if not status["finished"]:
193
+ status["stage"] = "edge_memorization"
194
+
195
+ m = _last_match(
196
+ r"Path Epoch (\d+)/(\d+):\s*.*?acc=([0-9.]+)%,\s*loss=([0-9.]+)",
197
+ text,
198
+ )
199
+ if m:
200
+ status["path"] = {
201
+ "epoch": int(m.group(1)),
202
+ "total": int(m.group(2)),
203
+ "acc_pct": float(m.group(3)),
204
+ "loss": float(m.group(4)),
205
+ "frac": int(m.group(1)) / max(int(m.group(2)), 1),
206
+ }
207
+ if not status["finished"]:
208
+ status["stage"] = "path_finetuning"
209
+
210
+ # mixed_full_path recipe logs "Joint Epoch"
211
+ m = _last_match(
212
+ r"Joint Epoch (\d+)/(\d+):\s*.*?acc=([0-9.]+)%,\s*loss=([0-9.]+)",
213
+ text,
214
+ )
215
+ if m:
216
+ status["path"] = {
217
+ "epoch": int(m.group(1)),
218
+ "total": int(m.group(2)),
219
+ "acc_pct": float(m.group(3)),
220
+ "loss": float(m.group(4)),
221
+ "frac": int(m.group(1)) / max(int(m.group(2)), 1),
222
+ "kind": "joint_mixed",
223
+ }
224
+ if not status["finished"]:
225
+ status["stage"] = "joint_mixed_training"
226
+
227
+ m = _last_match(r"Epoch (\d+) \| Test Acc: ([0-9.]+)%", text)
228
+ if m:
229
+ status["last_test_acc"] = {"epoch": int(m.group(1)), "acc_pct": float(m.group(2))}
230
+
231
+ m = _last_match(r"Forced Acc: ([0-9.]+)", text)
232
+ if m:
233
+ try:
234
+ status["forced_acc"] = float(m.group(1))
235
+ except ValueError:
236
+ pass
237
+
238
+ m = _last_match(r"Best test accuracy:\s*([0-9.]+)%", text)
239
+ if m:
240
+ status["best_test_acc"] = float(m.group(1))
241
+
242
+ if "Starting path" in text or "PATH FINETUNING" in text.upper() or "Path finetuning" in text:
243
+ if status["stage"] == "edge_memorization" and status.get("path"):
244
+ status["stage"] = "path_finetuning"
245
+ elif status["stage"] == "unknown" and not status["finished"]:
246
+ status["stage"] = "path_finetuning"
247
+
248
+ if "EDGE MEMORIZATION TRAINING" in text and status["stage"] == "unknown":
249
+ status["stage"] = "edge_memorization"
250
+
251
+ # clean recent non-tqdm-ish lines from absolute end
252
+ lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
253
+ interesting = [
254
+ ln
255
+ for ln in lines
256
+ if any(
257
+ k in ln
258
+ for k in (
259
+ "Edge Epoch",
260
+ "Path Epoch",
261
+ "Test Acc",
262
+ "Best test",
263
+ "Final checkpoint",
264
+ "Training finished",
265
+ "INFO",
266
+ "ERROR",
267
+ )
268
+ )
269
+ ]
270
+ status["recent_lines"] = interesting[-8:]
271
+ return status
272
+
273
+
274
+ def progress_bar(frac: float, width: int = 28) -> str:
275
+ frac = max(0.0, min(1.0, frac))
276
+ filled = int(round(frac * width))
277
+ return "[" + "#" * filled + "-" * (width - filled) + f"] {frac*100:5.1f}%"
278
+
279
+
280
+ def build_snapshot(log_path: Path) -> dict:
281
+ procs = find_training_processes()
282
+ log_status = parse_log(log_path)
283
+ snap = {
284
+ "updated_at": _now(),
285
+ "running": bool(procs) and not log_status.get("finished"),
286
+ "processes": procs,
287
+ "gpu": gpu_snapshot(),
288
+ "log": log_status,
289
+ }
290
+ return snap
291
+
292
+
293
+ def format_text(snap: dict) -> str:
294
+ log = snap["log"]
295
+ lines = []
296
+ lines.append("=" * 60)
297
+ lines.append("ICML Repro — Claim 1 training status")
298
+ lines.append(f"Updated: {snap['updated_at']}")
299
+ lines.append("=" * 60)
300
+
301
+ if snap["processes"]:
302
+ for p in snap["processes"]:
303
+ lines.append(
304
+ f"PID {p['pid']} elapsed={p['etime']} cpu={p['pcpu']}% "
305
+ f"mem={p['pmem']}% running"
306
+ )
307
+ lines.append(f" {p['cmd']}")
308
+ else:
309
+ lines.append("No train_in_weights.py process found.")
310
+
311
+ if snap.get("gpu"):
312
+ g = snap["gpu"]
313
+ lines.append(
314
+ f"GPU: {g['name']} util={g['util_pct']:.0f}% "
315
+ f"mem={g['mem_used_mib']:.0f}/{g['mem_total_mib']:.0f} MiB"
316
+ )
317
+
318
+ lines.append(f"Stage: {log.get('stage')}")
319
+ lines.append(f"Finished: {log.get('finished')}")
320
+ if log.get("graph"):
321
+ lines.append(f"Graph: {log['graph']}")
322
+ if log.get("model_params"):
323
+ lines.append(f"Params: {log['model_params']}")
324
+ if log.get("device"):
325
+ lines.append(f"Device: {log['device']}")
326
+
327
+ if log.get("edge"):
328
+ e = log["edge"]
329
+ lines.append(
330
+ f"Edge: epoch {e['epoch']}/{e['total']} "
331
+ f"acc={e['acc_pct']:.2f}% loss={e['loss']:.4f}"
332
+ )
333
+ lines.append(" " + progress_bar(e["frac"]))
334
+ if log.get("path"):
335
+ p = log["path"]
336
+ lines.append(
337
+ f"Path: epoch {p['epoch']}/{p['total']} "
338
+ f"acc={p['acc_pct']:.2f}% loss={p['loss']:.4f}"
339
+ )
340
+ lines.append(" " + progress_bar(p["frac"]))
341
+ if log.get("last_test_acc") is not None:
342
+ t = log["last_test_acc"]
343
+ lines.append(f"Last test acc: {t['acc_pct']:.2f}% (epoch {t['epoch']})")
344
+ if log.get("best_test_acc") is not None:
345
+ lines.append(f"Best test acc: {log['best_test_acc']:.2f}%")
346
+
347
+ lines.append(f"Log: {log.get('log_path')} ({log.get('log_bytes', 0)} bytes)")
348
+ if log.get("run_dir"):
349
+ lines.append(f"Run dir: {log['run_dir']}")
350
+ lines.append("-" * 60)
351
+ lines.append("Tip: tail -f logs_claim1_medium.log")
352
+ lines.append(" python repro/scripts/training_status.py --watch")
353
+ lines.append("Logbook UI: http://localhost:7861/")
354
+ lines.append("=" * 60)
355
+ return "\n".join(lines)
356
+
357
+
358
+ def format_markdown(snap: dict) -> str:
359
+ log = snap["log"]
360
+ running = "🟢 **running**" if snap["running"] else (
361
+ "✅ **finished**" if log.get("finished") else "⚪ **idle / unknown**"
362
+ )
363
+ parts = [
364
+ f"### Live training status",
365
+ f"_Auto-updated: {snap['updated_at']}_ · {running}",
366
+ "",
367
+ ]
368
+ if snap["processes"]:
369
+ p = snap["processes"][0]
370
+ parts.append(f"- **PID:** `{p['pid']}` · elapsed `{p['etime']}` · CPU `{p['pcpu']}%`")
371
+ if snap.get("gpu"):
372
+ g = snap["gpu"]
373
+ parts.append(
374
+ f"- **GPU:** {g['name']} · util `{g['util_pct']:.0f}%` · "
375
+ f"mem `{g['mem_used_mib']:.0f}/{g['mem_total_mib']:.0f}` MiB"
376
+ )
377
+ parts.append(f"- **Stage:** `{log.get('stage')}`")
378
+ if log.get("edge"):
379
+ e = log["edge"]
380
+ parts.append(
381
+ f"- **Edge memorization:** epoch **{e['epoch']}/{e['total']}** · "
382
+ f"acc **{e['acc_pct']:.2f}%** · loss `{e['loss']:.4f}` \n"
383
+ f" `{progress_bar(e['frac'])}`"
384
+ )
385
+ if log.get("path"):
386
+ p = log["path"]
387
+ parts.append(
388
+ f"- **Path finetuning:** epoch **{p['epoch']}/{p['total']}** · "
389
+ f"acc **{p['acc_pct']:.2f}%** · loss `{p['loss']:.4f}` \n"
390
+ f" `{progress_bar(p['frac'])}`"
391
+ )
392
+ if log.get("last_test_acc"):
393
+ t = log["last_test_acc"]
394
+ parts.append(f"- **Last held-out test acc:** **{t['acc_pct']:.2f}%** (epoch {t['epoch']})")
395
+ if log.get("best_test_acc") is not None:
396
+ parts.append(f"- **Best test acc:** **{log['best_test_acc']:.2f}%**")
397
+ if log.get("graph"):
398
+ parts.append(f"- **Graph:** `{log['graph']}`")
399
+ parts.append(f"- **Log file:** `logs_claim1_medium.log`")
400
+ parts.append("")
401
+ parts.append(
402
+ "Watch in terminal: `python repro/scripts/training_status.py --watch` · "
403
+ "or `tail -f logs_claim1_medium.log`"
404
+ )
405
+ return "\n".join(parts)
406
+
407
+
408
+ def format_html(snap: dict) -> str:
409
+ mdish = format_markdown(snap).replace("\n", "<br>\n")
410
+ # simple HTML, auto-refresh every 10s if opened in browser
411
+ return f"""<!doctype html>
412
+ <html><head>
413
+ <meta charset="utf-8"/>
414
+ <meta http-equiv="refresh" content="10"/>
415
+ <title>Claim 1 training status</title>
416
+ <style>
417
+ body {{ font-family: ui-sans-serif, system-ui, sans-serif; margin: 1.5rem; max-width: 720px; }}
418
+ code {{ background: #f4f4f5; padding: 0.1rem 0.3rem; border-radius: 4px; }}
419
+ .box {{ border: 1px solid #e4e4e7; border-radius: 12px; padding: 1rem 1.25rem; }}
420
+ h1 {{ font-size: 1.25rem; }}
421
+ </style>
422
+ </head>
423
+ <body>
424
+ <h1>Claim 1 — training status</h1>
425
+ <p>Auto-refreshes every 10s. Generated {_now()}.</p>
426
+ <div class="box">{mdish}</div>
427
+ <p><a href="http://localhost:7861/">Open Trackio logbook</a></p>
428
+ </body></html>
429
+ """
430
+
431
+
432
+ def write_status_files(snap: dict) -> None:
433
+ STATUS_JSON.parent.mkdir(parents=True, exist_ok=True)
434
+ STATUS_JSON.write_text(json.dumps(snap, indent=2))
435
+ STATUS_MD.write_text(format_markdown(snap) + "\n")
436
+ STATUS_HTML.write_text(format_html(snap))
437
+
438
+
439
+ def update_logbook_page(snap: dict) -> bool:
440
+ """Rewrite the live-status block inside the Claim 1 page markdown."""
441
+ if not CLAIM1_PAGE.exists():
442
+ return False
443
+ body = format_markdown(snap)
444
+ block = f"{LIVE_BEGIN}\n\n{body}\n\n{LIVE_END}"
445
+ text = CLAIM1_PAGE.read_text(encoding="utf-8")
446
+
447
+ if LIVE_BEGIN in text and LIVE_END in text:
448
+ pre, rest = text.split(LIVE_BEGIN, 1)
449
+ _, post = rest.split(LIVE_END, 1)
450
+ new_text = pre + block + post
451
+ else:
452
+ # Insert a trackio-style markdown cell near the top (after title)
453
+ cell = (
454
+ "\n\n---\n"
455
+ "<!-- trackio-cell\n"
456
+ '{"type": "markdown", "id": "cell_live_training_status", '
457
+ f'"created_at": "{datetime.now(timezone.utc).isoformat()}", '
458
+ '"title": "Live training status"}\n'
459
+ "-->\n"
460
+ f"{block}\n"
461
+ )
462
+ # after first heading block
463
+ if "\n\n" in text:
464
+ head, tail = text.split("\n\n", 1)
465
+ new_text = head + "\n\n" + cell + "\n" + tail
466
+ else:
467
+ new_text = text + cell
468
+
469
+ CLAIM1_PAGE.write_text(new_text, encoding="utf-8")
470
+
471
+ # bump logbook.json updated_at so the UI notices
472
+ lb = ROOT / ".trackio" / "logbook" / "logbook.json"
473
+ if lb.exists():
474
+ try:
475
+ data = json.loads(lb.read_text())
476
+ data["updated_at"] = datetime.now(timezone.utc).isoformat()
477
+ lb.write_text(json.dumps(data, indent=2))
478
+ except Exception:
479
+ pass
480
+ return True
481
+
482
+
483
+ def once(log_path: Path, logbook: bool, quiet: bool = False) -> dict:
484
+ snap = build_snapshot(log_path)
485
+ write_status_files(snap)
486
+ if logbook:
487
+ update_logbook_page(snap)
488
+ if not quiet:
489
+ print(format_text(snap))
490
+ print(f"\nWrote {STATUS_JSON.relative_to(ROOT)}")
491
+ print(f"Wrote {STATUS_MD.relative_to(ROOT)}")
492
+ print(f"Wrote {STATUS_HTML.relative_to(ROOT)} (open in browser; auto-refresh 10s)")
493
+ if logbook:
494
+ print(f"Updated logbook page: {CLAIM1_PAGE.relative_to(ROOT)}")
495
+ print("Refresh http://localhost:7861/ → Claim 1")
496
+ return snap
497
+
498
+
499
+ def main(argv=None) -> int:
500
+ parser = argparse.ArgumentParser(description=__doc__)
501
+ parser.add_argument("--log", type=Path, default=DEFAULT_LOG, help="Training log path")
502
+ parser.add_argument("--watch", action="store_true", help="Refresh continuously")
503
+ parser.add_argument("--interval", type=float, default=5.0, help="Watch interval seconds")
504
+ parser.add_argument(
505
+ "--logbook",
506
+ action="store_true",
507
+ help="Rewrite live status block on Claim 1 logbook page",
508
+ )
509
+ parser.add_argument(
510
+ "--json",
511
+ action="store_true",
512
+ help="Print JSON snapshot only",
513
+ )
514
+ args = parser.parse_args(argv)
515
+
516
+ stop = False
517
+
518
+ def _sig(_s, _f):
519
+ nonlocal stop
520
+ stop = True
521
+
522
+ signal.signal(signal.SIGINT, _sig)
523
+ signal.signal(signal.SIGTERM, _sig)
524
+
525
+ if args.watch:
526
+ while not stop:
527
+ # clear screen for readable watch
528
+ if not args.json and sys.stdout.isatty():
529
+ os.system("clear" if os.name != "nt" else "cls")
530
+ snap = once(args.log, logbook=args.logbook, quiet=args.json)
531
+ if args.json:
532
+ print(json.dumps(snap, indent=2))
533
+ if snap["log"].get("finished") and not snap["running"]:
534
+ if not args.json:
535
+ print("\nTraining finished — exiting watch.")
536
+ break
537
+ # sleep in small chunks so Ctrl+C is snappy
538
+ end = time.time() + args.interval
539
+ while time.time() < end and not stop:
540
+ time.sleep(0.2)
541
+ return 0
542
+
543
+ snap = once(args.log, logbook=args.logbook, quiet=args.json)
544
+ if args.json:
545
+ print(json.dumps(snap, indent=2))
546
+ return 0
547
+
548
+
549
+ if __name__ == "__main__":
550
+ raise SystemExit(main())