pcmt-artifact / scripts /update_manuscript_metrics.py
Lightcap's picture
Add files using upload-large-folder tool
9fc0ed7 verified
Raw
History Blame Contribute Delete
6.37 kB
from __future__ import annotations
import argparse
import csv
import json
import re
from datetime import datetime
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PAPER = ROOT / "arxiv" / "paper.tex"
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--detector", default="runs/remote_gpu/benchmark-detector-gpu/traces.csv")
parser.add_argument("--detector-metrics", default="runs/remote_gpu/benchmark-detector-gpu/metrics.json")
parser.add_argument("--sweep", default="runs/remote_gpu/sweep-detector-gpu/sweep_traces.csv")
parser.add_argument("--metrics", default="runs/remote_gpu/sweep-detector-gpu/sweep_metrics.json")
parser.add_argument("--telemetry-dir", default="runs/remote_gpu")
args = parser.parse_args()
detector = _best_trace(ROOT / args.detector, telemetry_dir=ROOT / args.telemetry_dir, trace_name="traces.csv", metrics_name="metrics.json")
detector_metrics = detector.parent / "metrics.json" if detector is not None else ROOT / args.detector_metrics
sweep = _best_trace(ROOT / args.sweep, telemetry_dir=ROOT / args.telemetry_dir, trace_name="sweep_traces.csv", metrics_name="sweep_metrics.json")
metrics = sweep.parent / "sweep_metrics.json" if sweep is not None else ROOT / args.metrics
telemetry_dir = ROOT / args.telemetry_dir
updates: dict[str, str] = {}
if detector and detector.exists():
detector_rows, detector_clips = count_trace(detector)
updates["DetectorRows"] = str(detector_rows)
updates["DetectorClips"] = str(detector_clips)
if detector_metrics.exists():
data = json.loads(detector_metrics.read_text())
elapsed = float(data.get("elapsed_seconds", 0.0))
rows = int(data.get("rows", updates.get("DetectorRows", 0)))
if elapsed > 0 and rows > 0:
updates["DetectorThroughput"] = f"{rows / elapsed:.1f}"
if sweep and sweep.exists():
sweep_rows, _ = count_trace(sweep)
updates["SweepRows"] = str(sweep_rows)
if metrics.exists():
data = json.loads(metrics.read_text())
updates["SweepFalsePositive"] = f"{float(data.get('false_positive_mean', 0.0)):.3f}"
updates["SweepLocalization"] = f"{float(data.get('localization_error_mean', 0.0)):.2f}"
updates["SweepStability"] = f"{float(data.get('certificate_stability', 0.0)):.2f}"
if "rows" in data:
updates["SweepRows"] = str(int(data["rows"]))
if "clips" in data and "DetectorClips" not in updates:
updates["DetectorClips"] = str(int(data["clips"]))
telemetry = telemetry_summary(telemetry_dir)
if telemetry:
peak = telemetry["peak_util"]
current_peak = current_macro_int(PAPER, "GpuPeak")
if current_peak is not None:
peak = max(peak, current_peak)
updates["GpuPeak"] = str(int(round(peak)))
updates["GpuMean"] = str(int(round(telemetry["mean_util"])))
updates["GpuHours"] = f"{telemetry['hours']:.2f}"
updates["GpuVramPeak"] = f"{telemetry['peak_mem_mib'] / 1024.0:.1f}"
if not updates:
raise SystemExit("No metric inputs found; manuscript was not changed.")
rewrite_macros(PAPER, updates)
print(json.dumps(updates, indent=2, sort_keys=True))
return 0
def count_trace(path: Path) -> tuple[int, int]:
with path.open(newline="") as f:
reader = csv.DictReader(f)
rows = 0
videos: set[str] = set()
for row in reader:
rows += 1
if row.get("video_id"):
videos.add(row["video_id"])
return rows, len(videos)
def _best_trace(default: Path, telemetry_dir: Path, trace_name: str, metrics_name: str) -> Path | None:
candidates: list[Path] = []
if default.exists():
candidates.append(default)
if telemetry_dir.exists():
candidates.extend(path for path in telemetry_dir.glob(f"**/{trace_name}") if (path.parent / metrics_name).exists())
if not candidates:
return None
return max(candidates, key=lambda path: count_trace(path)[0])
def telemetry_summary(root: Path) -> dict[str, float] | None:
utils: list[int] = []
mems: list[int] = []
times: list[datetime] = []
for path in root.glob("**/gpu_telemetry*.csv"):
with path.open(newline="") as f:
for row in csv.reader(f):
if row and row[0].strip().lower() == "timestamp":
continue
timestamp = parse_timestamp(row[0]) if row else None
if timestamp is not None:
times.append(timestamp)
row_mem = None
for cell in row:
match = re.search(r"(\d+)\s*%", cell)
if match:
utils.append(int(match.group(1)))
mem_match = re.search(r"(\d+)\s*MiB", cell)
if mem_match and row_mem is None:
row_mem = int(mem_match.group(1))
if row_mem is not None:
mems.append(row_mem)
if not utils:
return None
hours = 0.0
if len(times) >= 2:
hours = max(0.0, (max(times) - min(times)).total_seconds() / 3600.0)
return {
"peak_util": float(max(utils)),
"mean_util": float(sum(utils) / len(utils)),
"peak_mem_mib": float(max(mems) if mems else 0),
"hours": hours,
}
def parse_timestamp(value: str) -> datetime | None:
value = value.strip()
for fmt in ("%Y/%m/%d %H:%M:%S.%f", "%Y/%m/%d %H:%M:%S"):
try:
return datetime.strptime(value, fmt)
except ValueError:
pass
return None
def current_macro_int(path: Path, name: str) -> int | None:
match = re.search(rf"\\newcommand{{\\{name}}}{{(\d+)}}", path.read_text())
return int(match.group(1)) if match else None
def rewrite_macros(path: Path, updates: dict[str, str]) -> None:
text = path.read_text()
for name, value in updates.items():
text, count = re.subn(
rf"\\newcommand{{\\{name}}}{{[^}}]*}}",
rf"\\newcommand{{\\{name}}}{{{value}}}",
text,
count=1,
)
if count == 0:
raise SystemExit(f"Macro not found: {name}")
path.write_text(text)
if __name__ == "__main__":
raise SystemExit(main())