File size: 8,634 Bytes
1199e9d
 
 
 
 
 
 
 
 
 
 
 
fa3502a
1199e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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())