File size: 25,010 Bytes
017730d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
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 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

GENERAL_QUESTION = "Given this AI-generated video, does it successfully the requirement of the prompt: '<|prompt|>'? Respond with 'Yes' or 'No', Answer 'Yes' if the video perfectly matches the description. Answer 'No' if the video clearly contradicts the description. The presence of additional elements in the video is acceptable as long as they do not conflict with the core description. Please provide a brief explanation for your answer. \nProvide your analysis and explanation in JSON with keys: answer (e.g., Yes or No), explanation."

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(
    num_frames: int,
    height: int,
    width: int,
    temporal_factor: int = 2,
    factor: int = 32,
    min_pixels: int = 128 * 128,
    max_pixels: int = 16 * 16 * 2 * 2 * 2 * 6144,
):
    if height < factor or width < factor:
        raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
    elif 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
    t_bar = math.ceil(num_frames / temporal_factor) * temporal_factor

    if t_bar * h_bar * w_bar > max_pixels:
        beta = math.sqrt((num_frames * 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 t_bar * h_bar * w_bar < min_pixels:
        beta = math.sqrt(min_pixels / (num_frames * 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(
            T,
            H,
            W,
            factor=32, # 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 get_no_token_id(tokenizer):
    for tok in ["No", " No", "no", " no"]:
        ids = tokenizer.encode(tok, add_special_tokens=False)
        if ids:
            return ids[0]
    raise RuntimeError("Cannot find a valid No 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.
    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,
    normalization_mode="local",
    global_scale=1.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)
    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)
    if normalization_mode == "local":
        heatmap_smooth = (heatmap_smooth - heatmap_smooth.min()) / (heatmap_smooth.max() - heatmap_smooth.min() + 1e-8)
    elif normalization_mode == "global":
        heatmap_smooth = np.clip(heatmap_smooth / max(float(global_scale), 1e-8), 0.0, 1.0)
    else:
        raise ValueError(f"Unsupported normalization_mode: {normalization_mode}")

    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 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_video_grad_heatmap(
    model,
    processor,
    video_tensor,
    question,
    merge_size,
    force_yes_target=False,
    heatmap_mode="local",
):
    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:
        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
        yes_token_id = get_yes_token_id(processor.tokenizer)
        no_token_id = get_no_token_id(processor.tokenizer)
        yes_logit = logits[0, target_pos, yes_token_id]
        no_logit = logits[0, target_pos, no_token_id]

        if heatmap_mode == "margin":
            target_token_id = yes_token_id
            target_score = yes_logit - no_logit
        else:
            if force_yes_target:
                target_token_id = yes_token_id
            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)

    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),
            "heatmap_mode": heatmap_mode,
            "target_score": float(target_score.detach().cpu().item()),
            "yes_logit": float(yes_logit.detach().cpu().item()),
            "no_logit": float(no_logit.detach().cpu().item()),
        },
    )


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/qwen3vl_objects_grad_heatmap_sel",
        help="Output directory for heatmaps.",
    )
    parser.add_argument("--model_path", type=str, default="/nfs/hub/Qwen3-VL-8B-Instruct")
    parser.add_argument("--num_frames", type=int, default=10)
    parser.add_argument("--resize_factor", type=int, default=32)
    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("--general_question", action="store_true")

    parser.add_argument(
        "--heatmap_mode",
        type=str,
        default="local",
        choices=["local", "global", "margin"],
        help="local: per-sample min-max; global: fixed-scale normalization; margin: use (yes_logit-no_logit) target with global normalization.",
    )
    parser.add_argument(
        "--global_norm_scale",
        type=float,
        default=1.0,
        help="Scale used by global/margin modes: heatmap = clip(raw / global_norm_scale, 0, 1).",
    )
    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]

    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]

    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", [])
        import pdb
        # pdb.set_trace()

        if args.general_question:
            prompt = data.get('prompt', [])
            if len(prompt) < 1:
                continue
            questions = [GENERAL_QUESTION.replace('<|prompt|>', prompt[0])]
            output_dir = Path(f'{args.output_dir}_general_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,
                heatmap_mode=args.heatmap_mode,
            )
            # 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,
                normalization_mode="local" if args.heatmap_mode == "local" else "global",
                global_scale=args.global_norm_scale,
                save_path=str(sample_out / "heatmap.png"),
            )
            saved_mp4 = save_overlay_mp4(video_uint8, heatmap, str(sample_out / "heatmap.mp4"), fps=4)
            overlay_frames_dir, original_frames_dir, saved_frames = save_frame_images(video_uint8, heatmap, sample_out)

            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),
                "heatmap_mode": args.heatmap_mode,
                "global_norm_scale": args.global_norm_scale,
                "blur_sigma": args.blur_sigma,
                "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()