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