Backup / VideoX-Fun /visualization /videoalign_gradient_heatmap.py
YFanwang's picture
Upload VideoX-Fun batch 31/62 (5000 files)
017730d verified
Raw History Blame Contribute Delete
18.9 kB
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": "<video>"},
{"type": "text", "text": question},
],
},
]
def compute_videoalign_grad_heatmap(inferencer, video_tensor, question, target_dim="TA"):
model = inferencer.model
processor = inferencer.processor
tokenizer = processor.tokenizer
messages = build_messages(question)
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
batch = processor(
text=[text],
images=None,
videos=[video_tensor],
return_tensors="pt",
do_rescale=False,
do_resize=False,
# do_sample_frames=False,
)
batch = inferencer._prepare_inputs(batch)
target_dim = target_dim.upper()
dim2idx = {"VQ": 0, "MQ": 1, "TA": 2}
if target_dim not in dim2idx:
raise ValueError(f"Unsupported target_dim: {target_dim}. Choose from VQ/MQ/TA.")
with torch.enable_grad():
model.zero_grad(set_to_none=True)
outputs = model(
return_dict=True,
output_hidden_states=True,
enable_input_grads=True,
**batch,
)
logits = outputs["logits"]
import pdb
# pdb.set_trace()
target_score = logits[0, dim2idx[target_dim]]
loss = -target_score
embeddings = outputs.get("inputs_embeds", None)
if embeddings is None:
if outputs.get("hidden_states", None) is None:
raise RuntimeError("Model forward did not return hidden_states with output_hidden_states=True.")
embeddings = outputs["hidden_states"][0]
if not embeddings.requires_grad:
raise RuntimeError("Differentiation target does not require grad. Check enable_input_grads path.")
grads = torch.autograd.grad(loss, embeddings, retain_graph=False)[0]
vid_pad_id = tokenizer.convert_tokens_to_ids("<|video_pad|>")
if vid_pad_id is None:
raise RuntimeError("Tokenizer has no <|video_pad|> token id.")
video_mask = batch["input_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)
score = {
"VQ": float(logits[0, 0].detach().cpu().item()),
"MQ": float(logits[0, 1].detach().cpu().item()),
"TA": float(logits[0, 2].detach().cpu().item()),
"target_dim": target_dim,
"target_score": float(target_score.detach().cpu().item()),
}
return (
saliency.detach().cpu(),
score,
batch["video_grid_thw"].detach().cpu(),
video_mask.detach().cpu(),
grads.detach().cpu(),
)
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/chunk/videoalign_objects_grad_heatmap_sel",
help="Output directory for heatmaps.",
)
parser.add_argument(
"--videoalign_ckpt",
type=str,
default="/nfs/ywang29/Reward_finetuning/VideoX-Fun/VideoAlign/checkpoints",
help="VideoAlign checkpoint directory (contains model_config.json).",
)
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("--target_dim", type=str, default="TA", choices=["VQ", "MQ", "TA", "vq", "mq", "ta"])
parser.add_argument("--save_pt", action="store_true", help="Save raw grads/video_mask/video_grid to grad_data.pt")
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:0" if torch.cuda.is_available() else "cpu"
dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
inferencer = VideoVLMRewardInference(args.videoalign_ckpt, device=device, dtype=dtype)
image_processor = getattr(inferencer.processor, "image_processor", None)
merge_size = int(getattr(image_processor, "merge_size", 2))
temporal_patch_size = int(getattr(image_processor, "temporal_patch_size", 2))
patch_size = int(getattr(image_processor, "patch_size", 14))
args.resize_factor = patch_size * merge_size
json_files = sorted(input_dir.glob("*.json"))
# json_files = [Path('/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-107-3.json')]
json_files = [Path('/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-106-7.json')]
json_files = [
# Path('/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-233-2.json'),
# Path('/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-172-7.json'),
Path('/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-141-5.json'),
]
json_files = [
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-30-2.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-36-1.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-40-2.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-42-0.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-43-1.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-47-1.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-54-7.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-82-2.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-80-2.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-83-7.json',
]
json_files = [
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-112-4.json',
'/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_objects/negative/sample-125-1.json',
]
json_files = [Path(json_file) for json_file in json_files]
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
if len(questions) == 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, raw_question in enumerate(questions):
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)
question = build_prompt(
raw_question,
inferencer.data_config.eval_dim,
inferencer.data_config.prompt_template_type,
)
try:
saliency, score, video_grid_thw, video_mask, grads = compute_videoalign_grad_heatmap(
inferencer=inferencer,
video_tensor=video_tensor,
question=question,
target_dim=args.target_dim,
)
except Exception as e:
with open(sample_out / "error.txt", "w", encoding="utf-8") as ef:
ef.write(str(e))
continue
try:
heatmap = plot_heatmap_from_token_grads(
input_video=video_tensor.detach().cpu(),
video_grid_thw=video_grid_thw,
token_grads=saliency,
save_path=str(sample_out / "heatmap.png"),
merge_size=merge_size,
temporal_patch_size=temporal_patch_size,
)
saved_mp4 = save_overlay_mp4(video_uint8, heatmap.numpy(), str(sample_out / "heatmap.mp4"), fps=4)
overlay_frames_dir, original_frames_dir, saved_frames = save_frame_images(
video_uint8, heatmap.numpy(), sample_out
)
except Exception as e:
with open(sample_out / "plot_error.txt", "w", encoding="utf-8") as ef:
ef.write(str(e))
saved_mp4 = False
saved_frames = 0
overlay_frames_dir = str(sample_out / "frames_overlay")
original_frames_dir = str(sample_out / "frames_original")
if args.save_pt:
torch.save(
{
"video_grid_thw": video_grid_thw,
"video_mask": video_mask,
"grads": grads,
"video_token_saliency": saliency,
},
sample_out / "grad_data.pt",
)
meta = {
"json_path": str(json_path),
"video_path": str(video_path),
"raw_question": raw_question,
"question": question,
"gt_answer": gt,
"videoalign_scores": score,
"video_grid_thw": video_grid_thw.reshape(-1, 3)[0].tolist(),
"num_video_tokens": int(saliency.numel()),
"merge_size": merge_size,
"temporal_patch_size": temporal_patch_size,
"saved_mp4": bool(saved_mp4),
"saved_frames": int(saved_frames),
"overlay_frames_dir": overlay_frames_dir,
"original_frames_dir": original_frames_dir,
}
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()