Download compute_motion_score.py from Sybilhhhhh/benchmark: direct link, hf CLI and curl.
- Browser
- Download file 17.5 kB
-
https://huggingface.co/datasets/Sybilhhhhh/benchmark/resolve/main/compute_motion_score.py
- Command line
-
hf download hf://datasets/Sybilhhhhh/benchmark/compute_motion_score.py
-
curl -L -o compute_motion_score.py https://huggingface.co/datasets/Sybilhhhhh/benchmark/resolve/main/compute_motion_score.py
17.5 kB
| #!/usr/bin/env python3 | |
| """ | |
| Estimate per-video motion scores using torchvision RAFT (Small) optical flow. | |
| v2 β Cross-video mega-batching architecture: | |
| - All frames resize to a FIXED resolution so frame-pairs from different | |
| videos can be stacked into one large GPU batch. | |
| - Multi-threaded decord decoding feeds a global pair queue. | |
| - GPU pulls mega-batches (default 256 pairs) for maximum utilisation. | |
| - Per-video scores are accumulated and flushed as each video completes. | |
| Usage: | |
| # Single GPU: | |
| python compute_motion_score.py | |
| # 8-way sharding across GPUs: | |
| CUDA_VISIBLE_DEVICES=0 python compute_motion_score.py --num_shards 8 --shard_id 0 | |
| CUDA_VISIBLE_DEVICES=1 python compute_motion_score.py --num_shards 8 --shard_id 1 | |
| ... | |
| Output: | |
| One .duckdb per shard under --output_dir, table ``motion_scores``. | |
| """ | |
| import argparse | |
| import logging | |
| import os | |
| import time | |
| import warnings | |
| from queue import Queue | |
| from threading import Thread | |
| # Avoid CPU over-subscription: keep math backends single-threaded. | |
| os.environ.setdefault("OMP_NUM_THREADS", "1") | |
| os.environ.setdefault("MKL_NUM_THREADS", "1") | |
| os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") | |
| os.environ.setdefault("NUMEXPR_NUM_THREADS", "1") | |
| os.environ.setdefault("VECLIB_MAXIMUM_THREADS", "1") | |
| os.environ.setdefault("BLIS_NUM_THREADS", "1") | |
| os.environ.setdefault("TORCH_NUM_THREADS", "1") | |
| import numpy as np | |
| import torch | |
| import torchvision.transforms.functional as TF | |
| from torchvision.models.optical_flow import Raft_Small_Weights, raft_small | |
| import duckdb | |
| from decord import VideoReader | |
| from decord import cpu as decord_cpu | |
| warnings.filterwarnings("ignore", category=FutureWarning) | |
| # ββ paths ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| SOURCE_DB = "/opt/huawei/explorer-env/dataset/Vidgen_data_hyy/0327_bench/input_video_meta.duckdb" | |
| OUTPUT_DIR = "/opt/huawei/explorer-env/dataset/Vidgen_data_hyy/0327_bench/motion_scores" | |
| VIDEO_PREFIX = "/opt/huawei/explorer-env/" | |
| RAFT_SMALL_CKPT = "/opt/huawei/explorer-env/dataset/Vidgen_data_hyy/models/raft_small_C_T_V2-01064c6d.pth" | |
| # ββ fixed resize target (β16:9, both divisible by 8) ββββββββββββββββββββββ | |
| FIXED_H = 128 | |
| FIXED_W = 224 | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CLI | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def parse_args(): | |
| p = argparse.ArgumentParser( | |
| description="Compute video motion scores via RAFT optical flow (mega-batch)" | |
| ) | |
| # Sharding | |
| p.add_argument("--num_shards", type=int, default=1) | |
| p.add_argument("--shard_id", type=int, default=0) | |
| # GPU | |
| p.add_argument("--gpu_id", type=int, default=0) | |
| # Sampling | |
| p.add_argument("--sample_fps", type=float, default=2.0, | |
| help="Temporal sampling rate (frames per second)") | |
| p.add_argument("--max_duration", type=float, default=10.0, | |
| help="Only use the first N seconds of each video") | |
| # Resize | |
| p.add_argument("--resize_h", type=int, default=FIXED_H) | |
| p.add_argument("--resize_w", type=int, default=FIXED_W) | |
| # Mega-batch (auto-capped based on resize dims to avoid cuDNN grid_sample limit) | |
| p.add_argument("--mega_batch", type=int, default=0, | |
| help="Frame-pairs per GPU forward (0 = auto-max based on resize dims)") | |
| # Torch compile | |
| p.add_argument("--compile", action="store_true", | |
| help="torch.compile the model (adds ~30s startup, faster steady-state)") | |
| # I/O parallelism | |
| p.add_argument("--decode_workers", type=int, default=20, | |
| help="Threads for video decoding") | |
| p.add_argument("--prefetch", type=int, default=32, | |
| help="Max decoded-video items buffered before GPU") | |
| # Persistence | |
| p.add_argument("--save_interval", type=int, default=500, | |
| help="Flush results to DuckDB every N completed videos") | |
| p.add_argument("--source_db", type=str, default=SOURCE_DB) | |
| p.add_argument("--output_dir", type=str, default=OUTPUT_DIR) | |
| p.add_argument("--video_prefix", type=str, default=VIDEO_PREFIX) | |
| # Debug | |
| p.add_argument("--max_videos", type=int, default=0, | |
| help="Process at most N videos (0 = all)") | |
| args = p.parse_args() | |
| # Auto-compute mega_batch ceiling from cuDNN grid_sample limit. | |
| # RAFT builds a correlation volume at 1/8 resolution; cuDNN's grid_sample | |
| # requires B Γ H_feat Γ W_feat β€ ~262144. | |
| h_feat = args.resize_h // 8 | |
| w_feat = args.resize_w // 8 | |
| cudnn_safe_max = 262144 // (h_feat * w_feat) | |
| if args.mega_batch <= 0: | |
| args.mega_batch = cudnn_safe_max | |
| elif args.mega_batch > cudnn_safe_max: | |
| args.mega_batch = cudnn_safe_max | |
| return args | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # DuckDB helpers | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def get_video_list(source_db: str, num_shards: int, shard_id: int) -> list: | |
| con = duckdb.connect(source_db, read_only=True) | |
| rows = con.execute( | |
| "SELECT video_path FROM videos WHERE video_path IS NOT NULL ORDER BY video_path" | |
| ).fetchall() | |
| con.close() | |
| return [r[0] for r in rows][shard_id::num_shards] | |
| def get_processed_set(db_path: str) -> set: | |
| if not os.path.exists(db_path): | |
| return set() | |
| con = duckdb.connect(db_path, read_only=True) | |
| try: | |
| rows = con.execute("SELECT video_path FROM motion_scores").fetchall() | |
| except duckdb.CatalogException: | |
| rows = [] | |
| con.close() | |
| return {r[0] for r in rows} | |
| def ensure_output_table(db_path: str): | |
| con = duckdb.connect(db_path) | |
| con.execute(""" | |
| CREATE TABLE IF NOT EXISTS motion_scores ( | |
| video_path VARCHAR PRIMARY KEY, | |
| motion_score DOUBLE, | |
| status VARCHAR, | |
| num_frames_sampled INTEGER | |
| ) | |
| """) | |
| con.close() | |
| def flush_results(db_path: str, results: list): | |
| con = duckdb.connect(db_path) | |
| con.executemany( | |
| "INSERT OR REPLACE INTO motion_scores VALUES (?, ?, ?, ?)", results | |
| ) | |
| con.close() | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Video decoding (worker threads) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _decode_video(video_path: str, sample_fps: float, | |
| max_duration: float, resize_h: int, resize_w: int): | |
| """Decode β sample β fixed resize β return (img1, img2) pair stacks. | |
| Returns | |
| ------- | |
| img1 : (P, 3, H, W) uint8 β first frames of each pair | |
| img2 : (P, 3, H, W) uint8 β second frames of each pair | |
| Or ``(None, None)`` when the video has fewer than 2 usable frames. | |
| """ | |
| vr = VideoReader(video_path, ctx=decord_cpu(0), num_threads=1) | |
| total = len(vr) | |
| if total < 2: | |
| return None, None | |
| fps = vr.get_avg_fps() | |
| max_frame = min(total, int(min(total / fps, max_duration) * fps)) | |
| step = max(1, round(fps / sample_fps)) | |
| indices = list(range(0, max_frame, step)) | |
| if len(indices) < 2: | |
| indices = [0, min(max_frame - 1, total - 1)] | |
| frames = vr.get_batch(indices) | |
| frames = torch.as_tensor(frames.asnumpy()) # (N, H, W, C) | |
| frames = frames.permute(0, 3, 1, 2) # (N, C, H, W) | |
| frames = TF.resize(frames, [resize_h, resize_w], antialias=True) | |
| return frames[:-1].contiguous(), frames[1:].contiguous() | |
| _SENTINEL = "__SENTINEL__" | |
| def _decoder_worker(task_q: Queue, result_q: Queue, video_prefix: str, | |
| sample_fps: float, max_duration: float, | |
| resize_h: int, resize_w: int): | |
| while True: | |
| vp = task_q.get() | |
| if vp is None: | |
| result_q.put(_SENTINEL) | |
| break | |
| full = os.path.join(video_prefix, vp) | |
| try: | |
| i1, i2 = _decode_video(full, sample_fps, max_duration, | |
| resize_h, resize_w) | |
| if i1 is None: | |
| result_q.put((vp, None, None, "too_short")) | |
| else: | |
| result_q.put((vp, i1, i2, None)) | |
| except Exception as e: | |
| result_q.put((vp, None, None, str(e)[:300])) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GPU mega-batch inference loop | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def gpu_loop(result_q: Queue, model, transforms, device: torch.device, | |
| mega_batch: int, n_workers: int, | |
| out_db: str, save_interval: int, log, total_todo: int): | |
| # ββ pair buffer (cross-video) ββ | |
| buf_vp: list[str] = [] | |
| buf_i1: list[torch.Tensor] = [] | |
| buf_i2: list[torch.Tensor] = [] | |
| # ββ per-video accumulator: vp β [sum_mag, count, expected, n_frames] ββ | |
| acc: dict[str, list] = {} | |
| finished: list[tuple] = [] | |
| n_ok = n_err = n_short = 0 | |
| videos_received = 0 | |
| videos_done = 0 | |
| sentinels = 0 | |
| t0 = time.time() | |
| # ------------------------------------------------------------------ | |
| def _forward_batch(vps, i1_list, i2_list): | |
| """Stack, transfer, infer, accumulate.""" | |
| nonlocal n_ok, videos_done | |
| i1 = torch.stack(i1_list) | |
| i2 = torch.stack(i2_list) | |
| i1, i2 = transforms(i1, i2) | |
| i1 = i1.pin_memory().to(device, non_blocking=True) | |
| i2 = i2.pin_memory().to(device, non_blocking=True) | |
| flow = model(i1, i2)[-1] # (B, 2, H, W) | |
| mags = flow.norm(dim=1).mean(dim=(1, 2)) # (B,) | |
| mags_cpu = mags.cpu() | |
| for j, vp in enumerate(vps): | |
| a = acc[vp] | |
| a[0] += mags_cpu[j].item() | |
| a[1] += 1 | |
| if a[1] == a[2]: | |
| score = a[0] / a[2] | |
| finished.append((vp, round(score, 4), "ok", a[3])) | |
| del acc[vp] | |
| n_ok += 1 | |
| videos_done += 1 | |
| def _drain_buffer(): | |
| """Process all full mega-batches sitting in the buffer.""" | |
| nonlocal buf_vp, buf_i1, buf_i2 | |
| while len(buf_vp) >= mega_batch: | |
| _forward_batch(buf_vp[:mega_batch], | |
| buf_i1[:mega_batch], | |
| buf_i2[:mega_batch]) | |
| buf_vp = buf_vp[mega_batch:] | |
| buf_i1 = buf_i1[mega_batch:] | |
| buf_i2 = buf_i2[mega_batch:] | |
| def _log_progress(): | |
| elapsed = time.time() - t0 | |
| speed = videos_done / elapsed if elapsed > 0 else 0 | |
| eta_h = (total_todo - videos_done) / speed / 3600 if speed > 0 else float("inf") | |
| log.info( | |
| f"Progress {videos_done}/{total_todo} ({100*videos_done/total_todo:.1f}%) | " | |
| f"ok={n_ok} err={n_err} short={n_short} | " | |
| f"{speed:.1f} vid/s | ETA {eta_h:.1f}h | " | |
| f"buf={len(buf_vp)} pending_videos={len(acc)}" | |
| ) | |
| # ββ main consumer loop ββββββββββββββββββββββββββββββββββββββββββββ | |
| while sentinels < n_workers: | |
| item = result_q.get() | |
| # sentinel --- | |
| if item is _SENTINEL: | |
| sentinels += 1 | |
| continue | |
| vp, i1, i2, err = item | |
| videos_received += 1 | |
| if err is not None: | |
| if err == "too_short": | |
| finished.append((vp, 0.0, "too_short", 0)) | |
| n_short += 1 | |
| else: | |
| finished.append((vp, -1.0, f"error:{err}", 0)) | |
| n_err += 1 | |
| videos_done += 1 | |
| else: | |
| n_pairs = i1.shape[0] | |
| n_frames = n_pairs + 1 | |
| acc[vp] = [0.0, 0, n_pairs, n_frames] | |
| for k in range(n_pairs): | |
| buf_vp.append(vp) | |
| buf_i1.append(i1[k]) | |
| buf_i2.append(i2[k]) | |
| _drain_buffer() | |
| # periodic flush & log | |
| if len(finished) >= save_interval: | |
| flush_results(out_db, finished) | |
| finished.clear() | |
| _log_progress() | |
| # ββ tail: flush remaining pairs in buffer βββββββββββββββββββββββββ | |
| if buf_vp: | |
| _forward_batch(buf_vp, buf_i1, buf_i2) | |
| buf_vp, buf_i1, buf_i2 = [], [], [] | |
| if finished: | |
| flush_results(out_db, finished) | |
| finished.clear() | |
| elapsed = time.time() - t0 | |
| speed = videos_done / elapsed if elapsed > 0 else 0 | |
| log.info( | |
| f"Finished: {videos_done} videos in {elapsed/3600:.2f}h | " | |
| f"ok={n_ok} err={n_err} short={n_short} | {speed:.1f} vid/s" | |
| ) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Main | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def main(): | |
| args = parse_args() | |
| torch.set_num_threads(1) | |
| torch.set_num_interop_threads(1) | |
| log = logging.getLogger(f"shard-{args.shard_id}") | |
| log.setLevel(logging.INFO) | |
| h = logging.StreamHandler() | |
| h.setFormatter(logging.Formatter( | |
| f"%(asctime)s [shard {args.shard_id}/{args.num_shards}] %(levelname)s: %(message)s", | |
| datefmt="%Y-%m-%d %H:%M:%S", | |
| )) | |
| log.addHandler(h) | |
| log.propagate = False | |
| os.makedirs(args.output_dir, exist_ok=True) | |
| out_db = os.path.join( | |
| args.output_dir, f"motion_scores_shard{args.shard_id:04d}.duckdb" | |
| ) | |
| # 1. Video list & resume ------------------------------------------------ | |
| log.info("Loading video list β¦") | |
| shard_videos = get_video_list(args.source_db, args.num_shards, args.shard_id) | |
| log.info(f"Videos in shard: {len(shard_videos)}") | |
| ensure_output_table(out_db) | |
| done = get_processed_set(out_db) | |
| todo = [v for v in shard_videos if v not in done] | |
| if args.max_videos > 0: | |
| todo = todo[: args.max_videos] | |
| log.info(f"Already done: {len(done)}, remaining: {len(todo)}") | |
| if not todo: | |
| log.info("Nothing to process β exiting.") | |
| return | |
| # 2. Model -------------------------------------------------------------- | |
| device = torch.device(f"cuda:{args.gpu_id}") | |
| weights = Raft_Small_Weights.DEFAULT | |
| model = raft_small(weights=None) | |
| model.load_state_dict( | |
| torch.load(RAFT_SMALL_CKPT, map_location="cpu", weights_only=True) | |
| ) | |
| model = model.to(device).eval() | |
| if args.compile: | |
| log.info("torch.compile β¦ (one-time, may take ~30 s)") | |
| model = torch.compile(model, mode="reduce-overhead") | |
| transforms = weights.transforms() | |
| log.info( | |
| f"RAFT-Small on {device} | mega_batch={args.mega_batch} | " | |
| f"resize={args.resize_h}Γ{args.resize_w} | compile={args.compile}" | |
| ) | |
| # 3. Decoder threads ---------------------------------------------------- | |
| task_q: Queue = Queue(maxsize=args.prefetch * 2) | |
| result_q: Queue = Queue(maxsize=args.prefetch) | |
| workers = [] | |
| for _ in range(args.decode_workers): | |
| t = Thread( | |
| target=_decoder_worker, daemon=True, | |
| args=(task_q, result_q, args.video_prefix, | |
| args.sample_fps, args.max_duration, | |
| args.resize_h, args.resize_w), | |
| ) | |
| t.start() | |
| workers.append(t) | |
| def _feeder(): | |
| for vp in todo: | |
| task_q.put(vp) | |
| for _ in range(args.decode_workers): | |
| task_q.put(None) | |
| Thread(target=_feeder, daemon=True).start() | |
| # 4. GPU mega-batch loop ------------------------------------------------ | |
| gpu_loop( | |
| result_q, model, transforms, device, | |
| mega_batch=args.mega_batch, | |
| n_workers=args.decode_workers, | |
| out_db=out_db, | |
| save_interval=args.save_interval, | |
| log=log, | |
| total_todo=len(todo), | |
| ) | |
| for t in workers: | |
| t.join(timeout=5) | |
| if __name__ == "__main__": | |
| main() | |