Download VideoX-Fun/visualization/qwen25vl_gradient_heatmap.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/VideoX-Fun/visualization/qwen25vl_gradient_heatmap.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/VideoX-Fun/visualization/qwen25vl_gradient_heatmap.py
-
curl -L -o qwen25vl_gradient_heatmap.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/VideoX-Fun/visualization/qwen25vl_gradient_heatmap.py
19 kB
| import argparse | |
| import json | |
| import os | |
| import re | |
| import math | |
| from torchvision import io, transforms | |
| from torchvision.transforms import InterpolationMode | |
| from pathlib import Path | |
| import pdb | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from tqdm import tqdm | |
| from transformers import AutoModelForImageTextToText, AutoProcessor | |
| try: | |
| import cv2 | |
| except ImportError: | |
| cv2 = None | |
| try: | |
| from scipy.ndimage import gaussian_filter | |
| except ImportError: | |
| gaussian_filter = None | |
| def smart_resize(height, width, factor=28, min_pixels=56 * 56, max_pixels=14 * 14 * 4 * 1280): | |
| import math | |
| 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 smart_resize( | |
| height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4 * 1280 | |
| ): | |
| """Rescales the image so that the following conditions are met: | |
| 1. Both dimensions (height and width) are divisible by 'factor'. | |
| 2. The total number of pixels is within the range ['min_pixels', 'max_pixels']. | |
| 3. The aspect ratio of the image is maintained as closely as possible. | |
| """ | |
| 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 h_bar, w_bar | |
| def resize_frames(frames, max_frame_pixels): | |
| B, C, T, H, W = frames.shape | |
| x = frames.permute(0, 2, 1, 3, 4) # [B, T, C, H, W] | |
| resized_height, resized_width = smart_resize( | |
| H, | |
| W, | |
| factor=28, # image factor | |
| min_pixels=16384, # 128*128 | |
| 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) | |
| frames_resized = torch.stack(frames_resized) | |
| return frames_resized | |
| def read_video(video_path, num_frames, resize_factor, min_pixels, max_pixels): | |
| try: | |
| import decord | |
| from decord import VideoReader, cpu | |
| except ImportError as e: | |
| raise ImportError("decord is required for reading videos. Please install decord.") from e | |
| 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 | |
| _, _, h0, w0 = video.shape | |
| video = resize_frames(video.unsqueeze(0), max_pixels).permute(0, 2, 1, 3, 4)[0] # [B, C, T, H, W] -> [B, T, C, H, W] | |
| return video | |
| def extract_yes_no_from_gt(gt_text): | |
| if not gt_text: | |
| return None | |
| try: | |
| obj = json.loads(gt_text) | |
| ans = str(obj.get("answer", "")).strip().lower() | |
| if ans in {"yes", "no"}: | |
| return ans | |
| except Exception: | |
| pass | |
| m = re.search(r'"answer"\s*:\s*"(Yes|No|yes|no)"', gt_text) | |
| if m: | |
| return m.group(1).lower() | |
| return None | |
| def token_id_set_for_yes_no(tokenizer, label=None): | |
| token_texts = [] | |
| if label == "yes": | |
| token_texts = ["Yes", "yes", " Yes", " yes"] | |
| elif label == "no": | |
| token_texts = ["No", "no", " No", " no"] | |
| else: | |
| token_texts = ["Yes", "yes", " Yes", " yes", "No", "no", " No", " no"] | |
| token_ids = set() | |
| for t in token_texts: | |
| ids = tokenizer.encode(t, add_special_tokens=False) | |
| if ids: | |
| token_ids.add(ids[0]) | |
| return token_ids | |
| def get_yes_token_id(tokenizer): | |
| for tok in ["Yes", " Yes", "yes", " yes"]: | |
| ids = tokenizer.encode(tok, add_special_tokens=False) | |
| if ids: | |
| return ids[0] | |
| raise RuntimeError("Cannot find a valid Yes token id in tokenizer.") | |
| def find_yes_no_index_at_end(input_ids_1d, tokenizer, answer_label=None, search_window=256): | |
| seq = input_ids_1d.tolist() if hasattr(input_ids_1d, "tolist") else list(input_ids_1d) | |
| im_start_id = tokenizer.convert_tokens_to_ids("<|im_start|>") | |
| target_ids = token_id_set_for_yes_no(tokenizer, label=answer_label) | |
| # Align with preprocess logic: search backward near the end. | |
| # pdb.set_trace() | |
| start_pos = len(seq) - 1 | |
| end_pos = max(0, len(seq) - search_window) | |
| for i in range(start_pos, end_pos, -1): | |
| token_id = seq[i] | |
| if token_id == im_start_id: | |
| break | |
| if token_id in target_ids: | |
| return i | |
| return None | |
| def infer_token_grid(video_grid_thw, token_count, merge_size): | |
| grid_t, grid_h, grid_w = [int(x) for x in video_grid_thw] | |
| cands = [] | |
| if merge_size > 0 and grid_h % merge_size == 0 and grid_w % merge_size == 0: | |
| cands.append((grid_t, grid_h // merge_size, grid_w // merge_size)) | |
| cands.append((grid_t, grid_h, grid_w)) | |
| for t, h, w in cands: | |
| if t * h * w == token_count: | |
| return t, h, w | |
| raise ValueError( | |
| f"Cannot match token_count={token_count} with video_grid={video_grid_thw} and merge_size={merge_size}" | |
| ) | |
| def plot_smooth_heatmap_with_merge_correction( | |
| input_video, | |
| video_grid, | |
| token_grads, | |
| merge_size=2, | |
| blur_sigma=5.0, | |
| save_path="heatmap_smooth.png" | |
| ): | |
| """ | |
| blur_sigma: 高斯模糊的半径。 | |
| 如果是一个 float (e.g., 5.0),则在时间、高度、宽度上应用相同的模糊。 | |
| 如果是一个 tuple (e.g., (1.5, 8.0, 8.0)),则分别对应 (T, H, W) 方向的模糊程度。 | |
| """ | |
| T_in, C, H_in, W_in = input_video.shape | |
| grid_t, grid_h, grid_w = video_grid | |
| token_t = grid_t | |
| token_h = grid_h // merge_size | |
| token_w = grid_w // merge_size | |
| assert token_grads.numel() == token_t * token_h * token_w | |
| grads = token_grads.detach().cpu().float() | |
| if grads.dim() > 1: | |
| grads = grads.norm(dim=-1) | |
| grads = (grads - grads.min()) / (grads.max() - grads.min() + 1e-8) | |
| heatmap_small = grads.view(1, 1, token_t, token_h, token_w) | |
| heatmap_upsampled = F.interpolate( | |
| heatmap_small, | |
| size=(T_in, H_in, W_in), | |
| mode='trilinear', | |
| align_corners=False | |
| ).squeeze() | |
| heatmap_np = heatmap_upsampled.numpy() | |
| if isinstance(blur_sigma, float) or isinstance(blur_sigma, int): | |
| sigma_spatial = blur_sigma | |
| sigma_temporal = max(0.5, blur_sigma / 3.0) | |
| current_sigma = (sigma_temporal, sigma_spatial, sigma_spatial) | |
| else: | |
| current_sigma = blur_sigma | |
| heatmap_smooth = gaussian_filter(heatmap_np, sigma=current_sigma) | |
| heatmap_smooth = (heatmap_smooth - heatmap_smooth.min()) / (heatmap_smooth.max() - heatmap_smooth.min() + 1e-8) | |
| video_np = input_video.permute(0, 2, 3, 1).cpu().numpy() | |
| video_np = (video_np - video_np.min()) / (video_np.max() - video_np.min()) | |
| fig, axes = plt.subplots(2, T_in, figsize=(T_in * 2, 5)) | |
| plt.subplots_adjust(wspace=0.02, hspace=0.02, left=0.01, right=0.99) | |
| for t in range(T_in): | |
| img = video_np[t] | |
| hm = heatmap_smooth[t] | |
| ax_top = axes[0, t] | |
| ax_top.imshow(img) | |
| ax_top.imshow(hm, cmap='jet', alpha=0.5, vmin=0, vmax=1) | |
| ax_top.axis('off') | |
| ax_bot = axes[1, t] | |
| ax_bot.imshow(img) | |
| ax_bot.axis('off') | |
| if t == 0: | |
| ax_top.set_title("Smooth Heatmap", fontsize=10, x=-0.1, y=0.5, rotation=90) | |
| ax_bot.set_title("Original", fontsize=10, x=-0.1, y=0.5, rotation=90) | |
| ax_bot.text(0.5, -0.05, f"t={t}", transform=ax_bot.transAxes, ha='center', fontsize=8) | |
| plt.savefig(save_path, dpi=150, bbox_inches='tight') | |
| plt.close() | |
| return heatmap_smooth | |
| def save_overlay_png(video_uint8, heatmap, out_png): | |
| t_num = video_uint8.shape[0] | |
| fig, axes = plt.subplots(2, t_num, figsize=(max(10, t_num * 1.8), 4.5)) | |
| if t_num == 1: | |
| axes = np.array(axes).reshape(2, 1) | |
| plt.subplots_adjust(wspace=0.02, hspace=0.02, left=0.01, right=0.99) | |
| for t in range(t_num): | |
| ax0 = axes[0, t] | |
| ax0.imshow(video_uint8[t]) | |
| ax0.imshow(heatmap[t], cmap="jet", alpha=0.5, vmin=0, vmax=1) | |
| ax0.axis("off") | |
| ax1 = axes[1, t] | |
| ax1.imshow(video_uint8[t]) | |
| ax1.axis("off") | |
| ax1.text(0.5, -0.06, f"t={t}", transform=ax1.transAxes, ha="center", fontsize=8) | |
| axes[0, 0].set_title("Grad Heatmap", fontsize=10, x=-0.08, y=0.5, rotation=90) | |
| axes[1, 0].set_title("Original", fontsize=10, x=-0.08, y=0.5, rotation=90) | |
| plt.savefig(out_png, dpi=140, bbox_inches="tight") | |
| plt.close() | |
| 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 build_messages(question): | |
| return [ | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "video", "video": "<video>"}, | |
| {"type": "text", "text": question}, | |
| ], | |
| }, | |
| ] | |
| def compute_video_grad_heatmap(model, processor, video_tensor, question, merge_size, force_yes_target=False): | |
| messages = build_messages(question) | |
| text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| inputs = processor( | |
| text=[text], | |
| images=None, | |
| videos=[video_tensor], | |
| return_tensors="pt", | |
| do_rescale=False, | |
| do_resize=False, | |
| do_sample_frames=False, | |
| ).to(model.device) | |
| gen_kwargs = dict(max_new_tokens=512, output_hidden_states=True, return_dict_in_generate=True) | |
| generated = model.generate(**inputs, **gen_kwargs) | |
| generated_ids = generated["sequences"] | |
| generated_ids_trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, generated_ids)] | |
| output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True)[0] | |
| target_idx = find_yes_no_index_at_end(generated_ids[0], processor.tokenizer, answer_label=None) | |
| if target_idx is None: | |
| # import pdb | |
| # pdb.set_trace() | |
| raise RuntimeError("Cannot find Yes/No token in assistant span.") | |
| inputs_for_grad = { | |
| "input_ids": generated_ids, | |
| "pixel_values_videos": inputs["pixel_values_videos"], | |
| "video_grid_thw": inputs["video_grid_thw"], | |
| "attention_mask": torch.ones_like(generated_ids), | |
| } | |
| with torch.enable_grad(): | |
| model.zero_grad(set_to_none=True) | |
| outputs = model(**inputs_for_grad, output_hidden_states=True) | |
| embeddings = outputs.hidden_states[0] | |
| logits = outputs.logits | |
| target_pos = target_idx - 1 | |
| if force_yes_target: | |
| target_token_id = get_yes_token_id(processor.tokenizer) | |
| else: | |
| target_token_id = generated_ids[0, target_idx].item() | |
| target_score = logits[0, target_pos, target_token_id] | |
| grads = torch.autograd.grad(target_score, embeddings, retain_graph=False)[0] | |
| vid_pad_id = processor.tokenizer.convert_tokens_to_ids("<|video_pad|>") | |
| if vid_pad_id is None: | |
| raise RuntimeError("Tokenizer has no <|video_pad|> token id.") | |
| video_mask = (generated_ids[0] == vid_pad_id) | |
| video_grads = grads[0, video_mask] | |
| saliency = video_grads.norm(dim=-1) | |
| saliency = (saliency - saliency.min()) / (saliency.max() - saliency.min() + 1e-8) | |
| video_grid = inputs["video_grid_thw"][0].detach().cpu().tolist() | |
| t_in, _, h_in, w_in = video_tensor.shape | |
| return ( | |
| saliency.detach().cpu(), | |
| int(target_idx), | |
| int(target_token_id), | |
| video_grid, | |
| int(saliency.numel()), | |
| output_text, | |
| {"merge_size": merge_size, "force_yes_target": bool(force_yes_target)}, | |
| ) | |
| def load_json(path): | |
| with open(path, "r", encoding="utf-8") as f: | |
| return json.load(f) | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument( | |
| "--input_dir", | |
| type=str, | |
| default="/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative", | |
| help="Directory containing paired *.json and *.mp4.", | |
| ) | |
| parser.add_argument( | |
| "--output_dir", | |
| type=str, | |
| default="/nfs/ywang29/Reward_finetuning/VideoX-Fun/visualization/qwen25vl_objects_grad_heatmap_yes_target", | |
| help="Output directory for heatmaps.", | |
| ) | |
| parser.add_argument("--model_path", type=str, default="/nfs/hub/Qwen2.5-VL-7B-Instruct") | |
| parser.add_argument("--num_frames", type=int, default=10) | |
| parser.add_argument("--resize_factor", type=int, default=28) | |
| parser.add_argument("--min_pixels", type=int, default=128 * 128) | |
| parser.add_argument("--max_pixels", type=int, default=256*256) | |
| parser.add_argument("--merge_size", type=int, default=2) | |
| parser.add_argument("--blur_sigma", type=float, default=5.0) | |
| parser.add_argument("--force_yes_target", action="store_true") | |
| parser.add_argument("--max_samples", type=int, default=None) | |
| args = parser.parse_args() | |
| input_dir = Path(args.input_dir) | |
| output_dir = Path(args.output_dir) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| if not input_dir.exists(): | |
| raise FileNotFoundError(f"Input dir not found: {input_dir}") | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dtype = torch.bfloat16 if device == "cuda" else torch.float32 | |
| model = AutoModelForImageTextToText.from_pretrained( | |
| args.model_path, | |
| torch_dtype=dtype, | |
| attn_implementation="eager", | |
| device_map={"": device}, | |
| ) | |
| processor = AutoProcessor.from_pretrained(args.model_path) | |
| # Prefer processor resize config for Qwen-VL when available. | |
| if hasattr(processor, "video_processor") and processor.video_processor is not None: | |
| vp = processor.video_processor | |
| patch_size = int(getattr(vp, "patch_size", 14)) | |
| merge_size = int(getattr(vp, "merge_size", 2)) | |
| args.merge_size = merge_size | |
| args.resize_factor = patch_size * merge_size | |
| vp_size = getattr(vp, "size", None) | |
| # if isinstance(vp_size, dict): | |
| # args.min_pixels = int(vp_size.get("shortest_edge", args.min_pixels)) | |
| # args.max_pixels = int(vp_size.get("longest_edge", args.max_pixels)) | |
| json_files = sorted(input_dir.glob("*.json")) | |
| if args.max_samples is not None: | |
| json_files = json_files[: args.max_samples] | |
| for json_path in tqdm(json_files, desc="Processing"): | |
| stem = json_path.stem | |
| video_path = input_dir / f"{stem}.mp4" | |
| if not video_path.exists(): | |
| continue | |
| data = load_json(json_path) | |
| questions = data.get("question", []) | |
| gt_answers = data.get("gt_answer", []) | |
| if not isinstance(questions, list) or not isinstance(gt_answers, list): | |
| continue | |
| pair_count = len(questions) | |
| if pair_count == 0: | |
| continue | |
| video_tensor = read_video( | |
| str(video_path), | |
| args.num_frames, | |
| resize_factor=args.resize_factor, | |
| min_pixels=args.min_pixels, | |
| max_pixels=args.max_pixels, | |
| ) | |
| video_uint8 = (video_tensor.permute(0, 2, 3, 1).detach().cpu().numpy().clip(0, 1) * 255).astype(np.uint8) | |
| for i in range(pair_count): | |
| q = questions[i] | |
| gt = gt_answers[i] if i < len(gt_answers) else "" | |
| sample_out = output_dir / stem / f"q{i}" | |
| sample_out.mkdir(parents=True, exist_ok=True) | |
| try: | |
| saliency, idx, token_id, video_grid, num_video_tokens, output_text, restore_cfg = compute_video_grad_heatmap( | |
| model=model, | |
| processor=processor, | |
| video_tensor=video_tensor, | |
| question=q, | |
| merge_size=args.merge_size, | |
| force_yes_target=args.force_yes_target, | |
| ) | |
| except Exception as e: | |
| with open(sample_out / "error.txt", "w", encoding="utf-8") as ef: | |
| ef.write(str(e)) | |
| continue | |
| heatmap = plot_smooth_heatmap_with_merge_correction( | |
| video_tensor.detach().cpu(), | |
| video_grid, | |
| saliency, | |
| merge_size=args.merge_size, | |
| blur_sigma=args.blur_sigma, | |
| save_path=str(sample_out / "heatmap.png"), | |
| ) | |
| saved_mp4 = save_overlay_mp4(video_uint8, heatmap, str(sample_out / "heatmap.mp4"), fps=4) | |
| meta = { | |
| "json_path": str(json_path), | |
| "video_path": str(video_path), | |
| "question": q, | |
| "gt_answer": gt, | |
| "generated_answer_text": output_text, | |
| "yes_no_token_index": idx, | |
| "yes_no_token_id": token_id, | |
| "video_grid_thw": video_grid, | |
| "num_video_tokens": num_video_tokens, | |
| "restore_cfg": restore_cfg, | |
| "force_yes_target": bool(args.force_yes_target), | |
| "blur_sigma": args.blur_sigma, | |
| "saved_mp4": bool(saved_mp4), | |
| } | |
| with open(sample_out / "metadata.json", "w", encoding="utf-8") as f: | |
| json.dump(meta, f, ensure_ascii=False, indent=2) | |
| if __name__ == "__main__": | |
| main() | |