v15_benchmark / scripts /monitor_benchmark_feishu.py
Sumail's picture
Upload folder using huggingface_hub (part 11)
f789875 verified
Raw
History Blame Contribute Delete
12.4 kB
"""Feishu webhook monitor for long-running Perturb benchmarks.
Watches a benchmark output directory, counts completed samples, estimates ETA,
and sends Feishu (Lark) notifications on progress, abnormal exit, or completion.
Usage:
# Use env var for webhook
export FEISHU_WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/xxxx"
python scripts/monitor_benchmark_feishu.py \
--output-dir /workspace/Perturb/benchmark_2000_v15 \
--interval-minutes 30
# Or pass webhook directly
python scripts/monitor_benchmark_feishu.py \
--output-dir /workspace/Perturb/benchmark_2000_v15 \
--webhook https://open.feishu.cn/open-apis/bot/v2/hook/xxxx
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from datetime import datetime, timedelta
from pathlib import Path
import requests
def send_feishu(webhook_url: str, text: str) -> bool:
"""Send a plain text message to a Feishu webhook."""
if not webhook_url or webhook_url.startswith("https://YOUR_"):
print(f"[feishu skip] webhook not configured. Message would be:\n{text}")
return False
payload = {
"msg_type": "text",
"content": {"text": text},
}
try:
resp = requests.post(webhook_url, json=payload, timeout=10)
resp.raise_for_status()
print(f"[feishu ok] {resp.status_code} {resp.text[:120]}")
return True
except Exception as exc:
print(f"[feishu err] {exc}")
return False
def read_indices(output_dir: Path) -> tuple[int, list[int]] | None:
"""Return (total, indices) from indices.json if it exists."""
path = output_dir / "indices.json"
if not path.exists():
return None
try:
data = json.loads(path.read_text())
if isinstance(data, list):
return len(data), data
return int(data.get("n", 0)), data.get("indices", [])
except Exception as exc:
print(f"[warn] failed to read indices.json: {exc}")
return None
def count_completed(output_dir: Path, subdir: str) -> int:
"""Count completed *.json files under output_dir/subdir."""
target = output_dir / subdir
if not target.exists():
return 0
return len(list(target.glob("*.json")))
def read_summary(output_dir: Path, subdir: str) -> dict | None:
"""Read summary.json if available; fall back to aggregating summary_worker*.json."""
target_dir = output_dir / subdir
path = target_dir / "summary.json"
if path.exists():
try:
return json.loads(path.read_text())
except Exception:
pass
# Multi-worker mode: aggregate per-worker summaries.
worker_summaries = []
for ws_path in sorted(target_dir.glob("summary_worker*.json")):
try:
worker_summaries.append(json.loads(ws_path.read_text()))
except Exception:
pass
if not worker_summaries:
return None
total_n = sum(ws.get("n", 0) for ws in worker_summaries)
if total_n == 0:
return None
avg_score = sum(ws.get("avg_score", 0.0) * ws.get("n", 0) for ws in worker_summaries) / total_n
success_rate = sum(ws.get("success_rate", 0.0) * ws.get("n", 0) for ws in worker_summaries) / total_n
return {
"n": total_n,
"avg_score": avg_score,
"success_rate": success_rate,
"workers": len(worker_summaries),
"aggregated": True,
}
def process_alive(pids: list[int]) -> tuple[bool, list[int]]:
"""Return (any_alive, list_of_alive_pids)."""
alive = []
for pid in pids:
try:
os.kill(pid, 0)
alive.append(pid)
except (OSError, ProcessLookupError):
pass
return bool(alive), alive
def parse_pids(raw: str) -> list[int]:
"""Parse a comma-separated list of PIDs."""
return [int(x.strip()) for x in raw.split(",") if x.strip().isdigit()]
def load_pids_file(path: Path) -> list[int]:
"""Load PIDs from a file, one per line or comma-separated."""
if not path.exists():
return []
pids = []
for line in path.read_text().splitlines():
pids.extend(parse_pids(line))
return pids
def format_eta(seconds: float) -> str:
"""Format remaining seconds as a human readable string."""
if seconds < 0 or not seconds:
return "unknown"
delta = timedelta(seconds=int(seconds))
hours, remainder = divmod(delta.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
parts = []
if hours:
parts.append(f"{int(hours)}h")
if minutes:
parts.append(f"{int(minutes)}m")
if seconds or not parts:
parts.append(f"{int(seconds)}s")
return "".join(parts)
def build_progress_message(
*,
output_dir: Path,
subdir: str,
total: int,
completed: int,
pids: list[int],
elapsed_seconds: float,
) -> str:
"""Build a Feishu progress notification text."""
pct = completed / total * 100 if total else 0.0
avg_per_image = elapsed_seconds / completed if completed else 0.0
remaining = (total - completed) * avg_per_image if completed else 0.0
eta = format_eta(remaining)
summary = read_summary(output_dir, subdir)
score_line = ""
if summary:
avg = summary.get("avg_score", 0.0)
succ = summary.get("success_rate", 0.0) * 100
score_line = f"\n当前已跑完均分: {avg:.4f} | 成功率: {succ:.1f}%"
any_alive, alive_pids = process_alive(pids)
pid_line = f"PIDs: {','.join(str(p) for p in pids)}" if pids else "PID: not tracked"
status = f"running ({len(alive_pids)}/{len(pids)} workers alive)" if any_alive else "⚠️ all workers gone"
return (
f"🤖 Perturb benchmark 进度更新\n"
f"目录: {output_dir}/{subdir}\n"
f"{pid_line}\n"
f"状态: {status}\n"
f"进度: {completed}/{total} ({pct:.1f}%)\n"
f"已用时间: {format_eta(elapsed_seconds)}\n"
f"单图平均: {avg_per_image:.1f}s\n"
f"预计剩余: {eta}{score_line}"
)
def build_completion_message(
*,
output_dir: Path,
subdir: str,
total: int,
completed: int,
elapsed_seconds: float,
aborted: bool = False,
) -> str:
"""Build completion or abort notification text."""
summary = read_summary(output_dir, subdir)
if summary:
avg = summary.get("avg_score", 0.0)
succ = summary.get("success_rate", 0.0) * 100
score_line = f"均分: {avg:.4f} | 成功率: {succ:.1f}%"
else:
score_line = "summary.json 尚未生成"
if aborted:
emoji = "🚨"
header = "benchmark 异常退出"
extra = f"只完成了 {completed}/{total}"
else:
emoji = "✅"
header = "benchmark 已完成"
extra = f"全部 {total}/{total} 完成"
return (
f"{emoji} Perturb {header}\n"
f"目录: {output_dir}/{subdir}\n"
f"{extra}\n"
f"总耗时: {format_eta(elapsed_seconds)}\n"
f"{score_line}"
)
def monitor(
*,
output_dir: Path,
subdir: str,
webhook_url: str,
interval_seconds: float,
pids: list[int],
) -> None:
"""Main monitoring loop."""
indices_info = read_indices(output_dir)
if indices_info is None:
# Fallback: wait and retry a few times in case indices.json is not written yet.
for _ in range(10):
time.sleep(5)
indices_info = read_indices(output_dir)
if indices_info is not None:
break
if indices_info is None:
msg = f"❌ 监控启动失败:未找到 {output_dir}/indices.json"
send_feishu(webhook_url, msg)
raise RuntimeError(msg)
total, _ = indices_info
start_time = time.time()
last_report_time = start_time
last_completed = 0
# Initial notification
send_feishu(
webhook_url,
f"🚀 Perturb benchmark 监控已启动\n"
f"目录: {output_dir}/{subdir}\n"
f"总样本数: {total}\n"
f"推送间隔: {interval_seconds/60:.0f} 分钟\n"
f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
)
completed = count_completed(output_dir, subdir)
while True:
time.sleep(min(30, interval_seconds))
now = time.time()
elapsed = now - start_time
completed = count_completed(output_dir, subdir)
# Check if all watched processes died
any_alive, alive_pids = process_alive(pids)
if pids and not any_alive:
aborted = completed < total
msg = build_completion_message(
output_dir=output_dir,
subdir=subdir,
total=total,
completed=completed,
elapsed_seconds=elapsed,
aborted=aborted,
)
send_feishu(webhook_url, msg)
print(f"[monitor] all workers exited. completed={completed}/{total}")
return
# Periodic progress report
if now - last_report_time >= interval_seconds:
msg = build_progress_message(
output_dir=output_dir,
subdir=subdir,
total=total,
completed=completed,
pids=pids,
elapsed_seconds=elapsed,
)
send_feishu(webhook_url, msg)
last_report_time = now
# Detect completion
if completed >= total:
msg = build_completion_message(
output_dir=output_dir,
subdir=subdir,
total=total,
completed=completed,
elapsed_seconds=elapsed,
aborted=False,
)
send_feishu(webhook_url, msg)
print(f"[monitor] benchmark completed. {completed}/{total}")
return
# Print local heartbeat
if completed != last_completed:
print(
f"[{datetime.now().strftime('%H:%M:%S')}] completed={completed}/{total} "
f"elapsed={format_eta(elapsed)} alive_workers={len(alive_pids)}/{len(pids)}"
)
last_completed = completed
def main() -> None:
parser = argparse.ArgumentParser(description="Feishu monitor for Perturb benchmark")
parser.add_argument(
"--output-dir",
type=Path,
default=Path("/workspace/Perturb/benchmark_2000_v15"),
help="Benchmark output directory",
)
parser.add_argument(
"--subdir",
type=str,
default="v15",
help="Subdirectory containing per-image json files",
)
parser.add_argument(
"--webhook",
type=str,
default=os.getenv("FEISHU_WEBHOOK_URL", "https://open.feishu.cn/open-apis/bot/v2/hook/b1c64e78-6277-40e6-aed0-795a5c72deb6"),
help="Feishu webhook URL (or set FEISHU_WEBHOOK_URL env var)",
)
parser.add_argument(
"--interval-minutes",
type=float,
default=30.0,
help="Progress report interval in minutes",
)
parser.add_argument(
"--pid",
type=str,
default=None,
help="Comma-separated process IDs to watch (optional; auto-detected if omitted)",
)
args = parser.parse_args()
webhook = args.webhook
if not webhook:
print("[warn] FEISHU_WEBHOOK_URL not set; messages will be printed to stdout only.")
pids: list[int] = []
if args.pid:
pids = parse_pids(args.pid)
else:
# Try to auto-detect from pids.txt or legacy pid.txt next to the output dir.
candidates = [
args.output_dir.parent / f"{args.output_dir.name}_logs" / "pids.txt",
args.output_dir.parent / f"{args.output_dir.name}_logs" / "pid.txt",
args.output_dir / "pids.txt",
args.output_dir / "pid.txt",
]
for cand in candidates:
if cand.exists():
pids = load_pids_file(cand)
if pids:
print(f"[info] auto-detected pids={pids} from {cand}")
break
monitor(
output_dir=args.output_dir,
subdir=args.subdir,
webhook_url=webhook,
interval_seconds=args.interval_minutes * 60,
pids=pids,
)
if __name__ == "__main__":
main()