File size: 8,836 Bytes
12ea8f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Background watcher for the Kermany FM generation pipeline on h800."""

from __future__ import annotations

import json
import os
import re
import subprocess
import time
import urllib.request
from pathlib import Path


ROOT = Path("/data/temp/qinshengqian/c3")
DOWN = ROOT / "kermany_downstream"
BASE = Path(
    "/mnt/tidal-alsh-share2/dataset/qinshengqian/research/c3/Data/Classification/"
    "OCT_8/Baseline/RAE-main"
)
RESULTS = BASE / "results_kermany"
LOGDIR = RESULTS / "logs"
JSONS = DOWN / "jsons"
EVAL = DOWN / "eval"
STATUS = DOWN / "auto_monitor_status.json"
STATE_PATH = DOWN / "auto_monitor_state.json"
LOG_PATH = DOWN / "auto_monitor.log"
PID_PATH = DOWN / "auto_monitor.pid"

ARMS = ["RETFound", "VisionFM", "DINOv2L", "MAEL"]
EXPECTED_DOWNSTREAM = 12
INTERVAL = int(os.environ.get("KERMANY_MONITOR_INTERVAL", "600"))
STOP_ON_DONE = os.environ.get("KERMANY_MONITOR_STOP_ON_DONE", "1") == "1"

ERROR_PATTERNS = [
    "Traceback",
    "RuntimeError",
    "ChildFailedError",
    "CUDA out of memory",
    "No such file or directory",
    "EnvironmentNameNotFound",
    "ModuleNotFoundError",
    "AssertionError",
    "ValueError",
]


def run(cmd: str, timeout: int = 15) -> str:
    try:
        return subprocess.check_output(
            cmd, shell=True, stderr=subprocess.STDOUT, text=True, timeout=timeout
        )
    except subprocess.CalledProcessError as exc:
        return exc.output or ""
    except subprocess.TimeoutExpired as exc:
        return (exc.output or "") + "\n[TIMEOUT]"


def log(msg: str) -> None:
    ts = time.strftime("%Y-%m-%d %H:%M:%S")
    LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
    with LOG_PATH.open("a") as f:
        f.write(f"[{ts}] {msg}\n")


def load_state() -> dict:
    if STATE_PATH.exists():
        try:
            return json.loads(STATE_PATH.read_text())
        except Exception:
            return {}
    return {}


def save_state(state: dict) -> None:
    STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
    STATE_PATH.write_text(json.dumps(state, indent=2, ensure_ascii=False))


def send_feishu(title: str, body: str, color: str = "blue") -> None:
    cfg_path = Path.home() / ".codex" / "feishu.json"
    if not cfg_path.exists():
        return
    try:
        cfg = json.loads(cfg_path.read_text())
    except Exception:
        return
    if cfg.get("mode") in (None, "off"):
        return
    webhook = cfg.get("webhook_url")
    if not webhook:
        return
    payload = {
        "msg_type": "interactive",
        "card": {
            "header": {"title": {"tag": "plain_text", "content": title}, "template": color},
            "elements": [{"tag": "markdown", "content": body[:5000]}],
        },
    }
    try:
        req = urllib.request.Request(
            webhook,
            data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json"},
        )
        urllib.request.urlopen(req, timeout=8).read()
    except Exception as exc:
        log(f"feishu notification failed: {exc}")


def count_lines(path: Path) -> int:
    if not path.exists():
        return 0
    with path.open(errors="ignore") as f:
        return max(sum(1 for _ in f) - 1, 0)


def parse_latest_progress(path: Path) -> dict:
    if not path.exists():
        return {}
    text = run(f"tail -2000 {path}", timeout=10)
    matches = re.findall(r"\[Epoch (\d+) \| Step (\d+)\]", text)
    if not matches:
        return {}
    epoch, step = matches[-1]
    return {"epoch": int(epoch), "step": int(step)}


def collect_status() -> dict:
    procs = run(
        "ps -eo pid,etime,stat,cmd | grep -E "
        "'run_kermany_fm_pipeline|train_stage1.py|calculate_stat.py|src/train.py|"
        "kermany_dose_rn50|kermany_fm_sample|evaluate_quality' | grep -v grep || true"
    )
    gpu = run(
        "nvidia-smi --query-gpu=index,memory.used,memory.total,utilization.gpu "
        "--format=csv,noheader,nounits 2>/dev/null || true"
    )

    arms = {}
    for arm in ARMS:
        stage1_ckpt = RESULTS / "stage1" / f"stage1_{arm}" / "checkpoints" / "ep-last.pt"
        stat_file = RESULTS / "stats" / arm / "normalization_stats.pt"
        stage2_ckpt = RESULTS / "stage2" / f"stage2_{arm}" / "checkpoints" / "ep-last.pt"
        synth_csv = DOWN / "synth" / arm / "synth.csv"
        eval_json = EVAL / f"{arm}.json"
        dose = list(JSONS.glob(f"C-{arm}_d*.json"))
        full = list(JSONS.glob(f"C-{arm}_full_s*.json"))
        arms[arm] = {
            "stage1_done": stage1_ckpt.exists(),
            "stage1_progress": parse_latest_progress(LOGDIR / f"stage1_{arm}.log"),
            "stats_done": stat_file.exists(),
            "stage2_done": stage2_ckpt.exists(),
            "stage2_progress": parse_latest_progress(LOGDIR / f"stage2_{arm}.log"),
            "synth_rows": count_lines(synth_csv),
            "eval_done": eval_json.exists(),
            "downstream_json": len(dose) + len(full),
        }

    sdvae_json = len(list(JSONS.glob("C-sdvae_d*.json"))) + len(
        list(JSONS.glob("C-sdvae_full_s*.json"))
    )
    status = {
        "time": time.strftime("%Y-%m-%d %H:%M:%S"),
        "sdvae_done": (DOWN / "SDVAE_COMPLETION_DONE").exists(),
        "fm_done": (DOWN / "FM_PIPELINE_DONE").exists(),
        "sdvae_json": sdvae_json,
        "a_json": len(list(JSONS.glob("A_d*.json"))),
        "a_full_json": len(list(JSONS.glob("A_full_s*.json"))),
        "arms": arms,
        "process_lines": [line for line in procs.splitlines() if line.strip()],
        "gpu": [line for line in gpu.splitlines() if line.strip()],
    }
    return status


def summarize(status: dict) -> str:
    parts = []
    for arm, item in status["arms"].items():
        if item["downstream_json"] >= EXPECTED_DOWNSTREAM:
            stage = "downstream_done"
        elif item["synth_rows"] >= 8000:
            stage = "downstream"
        elif item["stage2_done"]:
            stage = "sample_eval"
        elif item["stats_done"]:
            stage = "stage2"
        elif item["stage1_done"]:
            stage = "stats"
        else:
            prog = item.get("stage1_progress") or {}
            if prog:
                stage = f"stage1_e{prog.get('epoch')}_s{prog.get('step')}"
            else:
                stage = "stage1_starting"
        parts.append(f"{arm}:{stage}")
    return "; ".join(parts)


def scan_new_errors(state: dict) -> list[str]:
    offsets = state.setdefault("log_offsets", {})
    files = [
        DOWN / "kermany_fm_pipeline.log",
        DOWN / "sdvae_completion.log",
    ]
    files.extend(LOGDIR.glob("*.log"))
    files.extend((DOWN / "logs").glob("*.log"))

    errors: list[str] = []
    for path in files:
        try:
            size = path.stat().st_size
        except FileNotFoundError:
            continue
        key = str(path)
        old = int(offsets.get(key, size))
        if size < old:
            old = 0
        if size > old:
            with path.open("r", errors="ignore") as f:
                f.seek(old)
                text = f.read(2_000_000)
            for line in text.splitlines():
                if any(pat in line for pat in ERROR_PATTERNS):
                    errors.append(f"{path.name}: {line[-500:]}")
        offsets[key] = size
    return errors[:20]


def main() -> None:
    DOWN.mkdir(parents=True, exist_ok=True)
    PID_PATH.write_text(str(os.getpid()))
    state = load_state()
    if not state:
        state = {"started_at": time.time(), "log_offsets": {}}
        scan_new_errors(state)
        save_state(state)
        log("monitor started")
        send_feishu("Kermany Monitor Started", "Kermany pipeline watcher is active.", "blue")

    while True:
        status = collect_status()
        summary = summarize(status)
        status["summary"] = summary
        errors = scan_new_errors(state)
        status["new_errors"] = errors
        STATUS.write_text(json.dumps(status, indent=2, ensure_ascii=False))

        last_summary = state.get("last_summary")
        last_done = state.get("last_done", False)
        if errors:
            log("ERRORS: " + " | ".join(errors[:3]))
            send_feishu("Kermany Pipeline Error", "\n".join(errors[:10]), "red")
        if summary != last_summary:
            log(f"progress: {summary}")
            send_feishu("Kermany Pipeline Progress", summary, "blue")
            state["last_summary"] = summary
        if status["fm_done"] and not last_done:
            body = "FM pipeline complete.\n\n" + summary
            log("FM pipeline complete")
            send_feishu("Kermany Pipeline Complete", body, "green")
            state["last_done"] = True
            save_state(state)
            if STOP_ON_DONE:
                break

        save_state(state)
        time.sleep(INTERVAL)


if __name__ == "__main__":
    main()