File size: 4,773 Bytes
d4101a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import json
import os
import runpy
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone

import truststore

truststore.inject_into_ssl()

RELEASED_SRC = r"C:\dev\AjudaEstudos\released\lua-nova-v1\src"
TIMINGS_PATH = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\timings.json"


def _poll_nvidia_smi(stop_event: threading.Event, stats: dict) -> None:
    while not stop_event.is_set():
        try:
            out = subprocess.check_output(
                ["nvidia-smi", "--query-gpu=memory.used,utilization.gpu", "--format=csv,noheader,nounits"],
                text=True,
                timeout=3,
            ).strip()
            if out:
                first_line = out.splitlines()[0]
                mem_s, util_s = [x.strip() for x in first_line.split(",")[:2]]
                mem_mib = int(mem_s)
                util = int(util_s)
                stats["max_nvidia_smi_mib"] = max(stats["max_nvidia_smi_mib"], mem_mib)
                stats["util_samples"].append(util)
        except Exception:
            pass
        stop_event.wait(2.0)


def main() -> None:
    parser = argparse.ArgumentParser(description="Run a lua_nova_v1 stage and log timing + VRAM metrics.")
    parser.add_argument("--stage", required=True, help="Stage identifier for timings.json")
    parser.add_argument("--module", required=True, help="Python module path, e.g. lua_nova_v1.training.stage1")
    parser.add_argument("module_args", nargs=argparse.REMAINDER, help="Arguments passed after -- to module")
    args = parser.parse_args()

    mod_args = list(args.module_args)
    if mod_args and mod_args[0] == "--":
        mod_args = mod_args[1:]

    if RELEASED_SRC not in sys.path:
        sys.path.insert(0, RELEASED_SRC)

    import torch

    if torch.cuda.is_available():
        torch.cuda.reset_peak_memory_stats()

    vram_stats = {"max_nvidia_smi_mib": 0, "util_samples": []}
    stop_event = threading.Event()
    poll_thread = threading.Thread(target=_poll_nvidia_smi, args=(stop_event, vram_stats), daemon=True)
    poll_thread.start()

    started_iso = datetime.now(timezone.utc).isoformat()
    t0 = time.perf_counter()
    exit_code = 0
    error_msg = None

    old_argv = sys.argv
    sys.argv = [args.module] + mod_args
    try:
        runpy.run_module(args.module, run_name="__main__")
    except SystemExit as exc:
        code = exc.code
        exit_code = 0 if code in (None, 0) else int(code) if isinstance(code, int) else 1
        if exit_code != 0:
            error_msg = f"SystemExit({code})"
    except Exception as exc:
        exit_code = 1
        error_msg = f"{type(exc).__name__}: {exc}"
        raise
    finally:
        sys.argv = old_argv
        elapsed_sec = time.perf_counter() - t0
        stop_event.set()
        poll_thread.join(timeout=3.0)
        ended_iso = datetime.now(timezone.utc).isoformat()

        peak_alloc_mib = (
            round(torch.cuda.max_memory_allocated() / (1024 * 1024), 1)
            if torch.cuda.is_available()
            else 0.0
        )
        peak_res_mib = (
            round(torch.cuda.max_memory_reserved() / (1024 * 1024), 1)
            if torch.cuda.is_available()
            else 0.0
        )
        mean_gpu_util = (
            round(sum(vram_stats["util_samples"]) / len(vram_stats["util_samples"]), 1)
            if vram_stats["util_samples"]
            else 0.0
        )

        record = {
            "stage": args.stage,
            "module": args.module,
            "args": mod_args,
            "started_utc": started_iso,
            "ended_utc": ended_iso,
            "duration_sec": round(elapsed_sec, 2),
            "duration_min": round(elapsed_sec / 60.0, 2),
            "peak_torch_allocated_mib": peak_alloc_mib,
            "peak_torch_reserved_mib": peak_res_mib,
            "peak_nvidia_smi_mib": vram_stats["max_nvidia_smi_mib"],
            "mean_gpu_util_pct": mean_gpu_util,
            "exit_code": exit_code,
            "error": error_msg,
        }

        if os.path.exists(TIMINGS_PATH):
            with open(TIMINGS_PATH, "r", encoding="utf-8") as fh:
                data = json.load(fh)
        else:
            data = {"stages": []}
        data["stages"].append(record)
        with open(TIMINGS_PATH, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False)

        print(
            f"\n[run_stage] stage={args.stage} exit={exit_code} "
            f"duration={elapsed_sec:.1f}s ({elapsed_sec/60:.2f}m) "
            f"peak_torch_alloc={peak_alloc_mib}MiB peak_smi={vram_stats['max_nvidia_smi_mib']}MiB",
            flush=True,
        )

    if exit_code != 0:
        sys.exit(exit_code)


if __name__ == "__main__":
    main()