import argparse import json import math import os import sys from pathlib import Path import matplotlib.pyplot as plt import numpy as np import torch import torch.nn.functional as tF from tqdm import tqdm from torchvision import transforms from torchvision.transforms import InterpolationMode try: import cv2 except ImportError: cv2 = None try: import decord from decord import VideoReader, cpu except ImportError: decord = None VIDEOALIGN_ROOT = Path(__file__).resolve().parents[1] / "VideoAlign" if str(VIDEOALIGN_ROOT) not in sys.path: sys.path.insert(0, str(VIDEOALIGN_ROOT)) from inference_flow_grpo import VideoVLMRewardInference # noqa: E402 from prompt_template import build_prompt # noqa: E402 def smart_resize(height, width, factor=28, min_pixels=56 * 56, max_pixels=14 * 14 * 4 * 1280): if max(height, width) / min(height, width) > 200: raise ValueError(f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}") h_bar = round(height / factor) * factor w_bar = round(width / factor) * factor if h_bar * w_bar > max_pixels: beta = math.sqrt((height * width) / max_pixels) h_bar = max(factor, math.floor(height / beta / factor) * factor) w_bar = max(factor, math.floor(width / beta / factor) * factor) elif h_bar * w_bar < min_pixels: beta = math.sqrt(min_pixels / (height * width)) h_bar = math.ceil(height * beta / factor) * factor w_bar = math.ceil(width * beta / factor) * factor return int(h_bar), int(w_bar) def resize_frames(frames, max_frame_pixels, resize_factor=28, min_pixels=128 * 128): bsz, channels, t_num, height, width = frames.shape x = frames.permute(0, 2, 1, 3, 4) resized_height, resized_width = smart_resize( height, width, factor=resize_factor, min_pixels=min_pixels, max_pixels=max_frame_pixels, ) frames_resized = [] for v in x: v_r = transforms.functional.resize( v, [resized_height, resized_width], interpolation=InterpolationMode.BICUBIC, antialias=True, ).float() frames_resized.append(v_r) del bsz, channels, t_num return torch.stack(frames_resized) def read_video(video_path, num_frames, resize_factor=28, min_pixels=128 * 128, max_pixels=256 * 256): if decord is None: raise ImportError("decord is required for reading videos. Please install decord.") decord.bridge.set_bridge("torch") vr = VideoReader(video_path, ctx=cpu(0)) total_frames = len(vr) if total_frames == 0: raise ValueError(f"Empty video: {video_path}") idx = torch.linspace(0, total_frames - 1, num_frames).round().long().tolist() video = vr.get_batch(idx).permute(0, 3, 1, 2).float() / 255.0 video = resize_frames(video.unsqueeze(0), max_pixels, resize_factor=resize_factor, min_pixels=min_pixels).permute(0, 2, 1, 3, 4)[0] return video def plot_heatmap_from_token_grads( input_video, video_grid_thw, token_grads, save_path, merge_size=2, temporal_patch_size=2, ): if isinstance(video_grid_thw, torch.Tensor): grid = video_grid_thw.reshape(-1, 3)[0].tolist() else: grid = list(video_grid_thw) if len(grid) != 3 and len(grid) > 0 and hasattr(grid[0], "__len__"): grid = list(grid[0]) grid_t, grid_h, grid_w = [int(x) for x in grid] grads = token_grads.detach().cpu().float() if grads.dim() > 1: grads = grads.norm(dim=-1) grads = grads.flatten() if grid_h % merge_size != 0 or grid_w % merge_size != 0: raise ValueError(f"grid_h/grid_w should be divisible by merge_size, got ({grid_h}, {grid_w}) vs {merge_size}") token_t, token_h, token_w = grid_t, grid_h // merge_size, grid_w // merge_size expected_tokens = token_t * token_h * token_w if grads.numel() != expected_tokens: raise ValueError(f"token count mismatch: grads={grads.numel()}, expected={expected_tokens}") grads = (grads - grads.min()) / (grads.max() - grads.min() + 1e-8) heatmap_small = grads.view(token_t, token_h, token_w) heatmap_small = heatmap_small.repeat_interleave(int(temporal_patch_size), dim=0) t_in, _, h_in, w_in = input_video.shape if heatmap_small.shape[0] < t_in: pad_t = t_in - heatmap_small.shape[0] heatmap_small = torch.cat([heatmap_small, heatmap_small[-1:].repeat(pad_t, 1, 1)], dim=0) elif heatmap_small.shape[0] > t_in: heatmap_small = heatmap_small[:t_in] heatmap_upsampled = tF.interpolate( heatmap_small.unsqueeze(1), size=(h_in, w_in), mode="bilinear", align_corners=False, ).squeeze(1) heatmap_upsampled = (heatmap_upsampled - heatmap_upsampled.min()) / ( heatmap_upsampled.max() - heatmap_upsampled.min() + 1e-8 ) video_np = input_video.detach().cpu().permute(0, 2, 3, 1).numpy() video_np = (video_np - video_np.min()) / (video_np.max() - video_np.min() + 1e-8) heatmap_np = heatmap_upsampled.numpy() cols = min(10, t_in) rows = math.ceil(t_in / cols) * 2 fig, axes = plt.subplots(rows, cols, figsize=(cols * 2.2, rows * 1.8)) axes = np.array(axes).reshape(rows, cols) for t in range(t_in): r_top = t // cols c = t % cols r_bottom = r_top + (rows // 2) ax_top = axes[r_top, c] ax_top.imshow(video_np[t]) ax_top.imshow(heatmap_np[t], cmap="jet", alpha=0.45, vmin=0, vmax=1) ax_top.axis("off") ax_top.set_title(f"F{t}", fontsize=8) ax_bot = axes[r_bottom, c] ax_bot.imshow(video_np[t]) ax_bot.axis("off") used_rows_per_half = math.ceil(t_in / cols) for r in range(rows): for c in range(cols): if r < used_rows_per_half: idx = r * cols + c else: idx = (r - used_rows_per_half) * cols + c if idx >= t_in: axes[r, c].axis("off") plt.tight_layout() plt.savefig(save_path, dpi=150, bbox_inches="tight") plt.close() return heatmap_upsampled def save_overlay_mp4(video_uint8, heatmap, out_mp4, fps=4): if cv2 is None: return False t_num, h, w, _ = video_uint8.shape writer = cv2.VideoWriter(out_mp4, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h)) for t in range(t_num): hm = plt.get_cmap("jet")(heatmap[t])[..., :3] frame = (0.5 * (video_uint8[t] / 255.0) + 0.5 * hm) * 255.0 frame = frame.astype(np.uint8) writer.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)) writer.release() return True def save_frame_images(video_uint8, heatmap, out_dir): out_dir = Path(out_dir) overlay_dir = out_dir / "frames_overlay" original_dir = out_dir / "frames_original" overlay_dir.mkdir(parents=True, exist_ok=True) original_dir.mkdir(parents=True, exist_ok=True) heatmap_np = heatmap if isinstance(heatmap, np.ndarray) else np.asarray(heatmap) t_num = video_uint8.shape[0] for t in range(t_num): hm_rgb = plt.get_cmap("jet")(heatmap_np[t])[..., :3] overlay = (0.5 * (video_uint8[t].astype(np.float32) / 255.0) + 0.5 * hm_rgb) * 255.0 overlay = np.clip(overlay, 0, 255).astype(np.uint8) if cv2 is not None: cv2.imwrite(str(overlay_dir / f"frame_{t:03d}.png"), cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR)) cv2.imwrite(str(original_dir / f"frame_{t:03d}.png"), cv2.cvtColor(video_uint8[t], cv2.COLOR_RGB2BGR)) else: plt.imsave(str(overlay_dir / f"frame_{t:03d}.png"), overlay) plt.imsave(str(original_dir / f"frame_{t:03d}.png"), video_uint8[t]) return str(overlay_dir), str(original_dir), t_num def build_messages(question): return [ { "role": "user", "content": [ {"type": "video", "video": "