#!/usr/bin/env python3 from __future__ import annotations import argparse import json import os import subprocess import sys import time from pathlib import Path DEFAULT_RAW_VIDEO_DIR = Path("/home/sf895/SignVerse-2M-runtime/raw_video") VIDEO_EXTENSIONS = (".mp4", ".mkv", ".webm", ".mov") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Benchmark DWpose CPU vs GPU on the same video and estimate CPU threads per 1 GPU." ) parser.add_argument("--video-id", type=str, required=True) parser.add_argument("--raw-video-dir", type=Path, default=DEFAULT_RAW_VIDEO_DIR) parser.add_argument("--fps", type=int, default=24) parser.add_argument("--max-frames", type=int, default=None) parser.add_argument( "--cpu-threads", type=str, default="1,2,4,8,16,32", help="Comma-separated CPU thread counts to benchmark.", ) parser.add_argument( "--device", choices=("cpu", "gpu"), default=None, help="Internal worker mode. Omit to run the controller.", ) parser.add_argument("--json", action="store_true", help="Emit final summary as JSON.") return parser.parse_args() def resolve_video_path(video_id: str, raw_video_dir: Path) -> Path: for ext in VIDEO_EXTENSIONS: candidate = raw_video_dir / f"{video_id}{ext}" if candidate.is_file(): return candidate raise FileNotFoundError(f"Video not found for {video_id} under {raw_video_dir}") def run_ffprobe_dims(video_path: Path) -> tuple[int, int]: proc = subprocess.run( [ "ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(video_path), ], check=True, capture_output=True, text=True, ) dims = (proc.stdout or "").strip() if "x" not in dims: raise RuntimeError(f"Unable to parse ffprobe dimensions: {dims!r}") width_s, height_s = dims.split("x", 1) return int(width_s), int(height_s) def stream_frames(video_path: Path, fps: int, max_frames: int | None): import numpy as np from PIL import Image width, height = run_ffprobe_dims(video_path) frame_bytes = width * height * 3 command = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-i", str(video_path), "-vf", f"fps={fps}", "-f", "rawvideo", "-pix_fmt", "rgb24", "pipe:1", ] proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) assert proc.stdout is not None frame_index = 0 stopped_early = False try: while True: if max_frames is not None and frame_index >= max_frames: stopped_early = True break chunk = proc.stdout.read(frame_bytes) if not chunk: break if len(chunk) != frame_bytes: raise RuntimeError( f"Short raw frame read: expected {frame_bytes} bytes, got {len(chunk)}" ) frame_index += 1 frame_array = np.frombuffer(chunk, dtype=np.uint8).reshape((height, width, 3)) yield frame_index, Image.fromarray(frame_array, mode="RGB") finally: if stopped_early and proc.poll() is None: proc.terminate() if proc.stdout: proc.stdout.close() stderr = proc.stderr.read().decode("utf-8", errors="replace") if proc.stderr else "" if proc.stderr: proc.stderr.close() returncode = proc.wait() if returncode != 0 and not stopped_early: raise RuntimeError(f"ffmpeg raw frame stream failed: {stderr.strip()}") def worker_main(args: argparse.Namespace) -> int: video_path = resolve_video_path(args.video_id, args.raw_video_dir) if args.device == "cpu": cpu_threads = int(os.environ.get("DWPOSE_CPU_THREADS", "1")) os.environ["OMP_NUM_THREADS"] = str(cpu_threads) os.environ["MKL_NUM_THREADS"] = str(cpu_threads) os.environ["OPENBLAS_NUM_THREADS"] = str(cpu_threads) os.environ["NUMEXPR_NUM_THREADS"] = str(cpu_threads) os.environ["ORT_NUM_THREADS"] = str(cpu_threads) from easy_dwpose import DWposeDetector device = "cpu" if args.device == "cpu" else "cuda:0" detector = DWposeDetector(device=device) start = time.perf_counter() frames = 0 for frame_index, frame in stream_frames(video_path, args.fps, args.max_frames): detector(frame, draw_pose=False, include_hands=True, include_face=True) frames = frame_index elapsed = time.perf_counter() - start result = { "video_id": args.video_id, "video_path": str(video_path), "device": args.device, "fps": args.fps, "max_frames": args.max_frames, "frames_processed": frames, "elapsed_seconds": elapsed, "frames_per_second": (frames / elapsed) if elapsed > 0 else 0.0, "cpu_threads": int(os.environ.get("DWPOSE_CPU_THREADS", "0")) if args.device == "cpu" else 0, "hostname": os.uname().nodename, } print(json.dumps(result, sort_keys=True)) return 0 def run_worker(script_path: Path, args: argparse.Namespace, device: str, cpu_threads: int | None = None) -> dict: env = os.environ.copy() if cpu_threads is not None: env["DWPOSE_CPU_THREADS"] = str(cpu_threads) cmd = [ sys.executable, str(script_path), "--video-id", args.video_id, "--raw-video-dir", str(args.raw_video_dir), "--fps", str(args.fps), "--device", device, ] if args.max_frames is not None: cmd.extend(["--max-frames", str(args.max_frames)]) proc = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) lines = [line.strip() for line in proc.stdout.splitlines() if line.strip()] if not lines: raise RuntimeError(f"No benchmark output returned for device={device}") return json.loads(lines[-1]) def controller_main(args: argparse.Namespace) -> int: script_path = Path(__file__).resolve() video_path = resolve_video_path(args.video_id, args.raw_video_dir) cpu_threads_list = [int(x) for x in args.cpu_threads.split(",") if x.strip()] gpu_result = run_worker(script_path, args, "gpu") cpu_results = [run_worker(script_path, args, "cpu", cpu_threads=t) for t in cpu_threads_list] summary = { "video_id": args.video_id, "video_path": str(video_path), "fps": args.fps, "max_frames": args.max_frames, "gpu_result": gpu_result, "cpu_results": [], } gpu_elapsed = gpu_result["elapsed_seconds"] for cpu_result in cpu_results: cpu_elapsed = cpu_result["elapsed_seconds"] cpu_threads = cpu_result["cpu_threads"] cpu_equivalent_threads = (cpu_threads * cpu_elapsed / gpu_elapsed) if gpu_elapsed > 0 else None merged = dict(cpu_result) merged["speedup_gpu_over_cpu"] = (cpu_elapsed / gpu_elapsed) if gpu_elapsed > 0 else None merged["approx_cpu_threads_for_one_gpu"] = cpu_equivalent_threads summary["cpu_results"].append(merged) if args.json: print(json.dumps(summary, indent=2, sort_keys=True)) return 0 print(f"video_id={summary['video_id']}") print(f"video_path={summary['video_path']}") print(f"fps={summary['fps']}") print(f"max_frames={summary['max_frames']}") print( "gpu_result " f"elapsed_seconds={gpu_result['elapsed_seconds']:.3f} " f"frames_processed={gpu_result['frames_processed']} " f"frames_per_second={gpu_result['frames_per_second']:.3f}" ) for row in summary["cpu_results"]: print( "cpu_result " f"threads={row['cpu_threads']} " f"elapsed_seconds={row['elapsed_seconds']:.3f} " f"frames_processed={row['frames_processed']} " f"frames_per_second={row['frames_per_second']:.3f} " f"speedup_gpu_over_cpu={row['speedup_gpu_over_cpu']:.3f} " f"approx_cpu_threads_for_one_gpu={row['approx_cpu_threads_for_one_gpu']:.2f}" ) return 0 def main() -> int: args = parse_args() if args.device is not None: return worker_main(args) return controller_main(args) if __name__ == "__main__": raise SystemExit(main())