File size: 31,310 Bytes
e3e1f6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Inference script for Qwen2.5-VL with token selection + insertion for PVSG/VIDOR data.

Key behaviors per user spec:
- Videos to evaluate are the ones that have a folder under `structured_json_root/{video_name}/`.
- Mask file per video: `{mask_root}/{video_name}_rle.json` (List[List[RLE]]).
- Only select objects that have a corresponding `{structured_json_root}/{video_name}/object_{id}.json`.
- Randomly sample up to `--max_objects` (default 20) objects from the above eligible set (with fixed seed).
- Record which object ids were sampled for each video.
- Build obj_masks (O, N, H_rz, W_rz) and run `select_tokens_fast` to get indices.
- Insert selected tokens with `rearrange_token` and run generation.
- Save outputs per video: the decoded text and a sidecar JSON recording sampled objects + metadata.

This script intentionally avoids reading each object_{id}.json contents; it only checks their existence.
"""

import os
import re
import json
import math
import argparse
import random
from dataclasses import dataclass
from typing import List, Tuple, Optional, Dict, Any
import glob


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from transformers import AutoProcessor, AutoTokenizer
from transformers.modeling_outputs import ModelOutput
from transformers.processing_utils import Unpack
from transformers.models.qwen2_5_vl.configuration_qwen2_5_vl import (
    Qwen2_5_VLConfig, Qwen2_5_VLTextConfig, Qwen2_5_VLVisionConfig
)
from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import (
    Qwen2_5_VLForConditionalGeneration,
    Qwen2_5_VLModel
)
from transformers.models.idefics2.modeling_idefics2 import Idefics2PerceiverResampler
from transformers.models.idefics2.configuration_idefics2 import Idefics2PerceiverConfig

from qwen_vl_vsg_utils.src.qwen_vl_utils import process_vision_info
from resampler_utils.token_selection import select_tokens
from resampler_utils.token_arrangement import rearrange_token

from pycocotools import mask as maskUtils

def find_video_path(video_root, video_name):
    pattern = os.path.join(video_root, f"{video_name}.[mM][pP]4")
    matches = glob.glob(pattern)
    if not matches:
        raise FileNotFoundError(f"No MP4 file found for {video_name} in {video_root}")
    return matches[0]

# -----------------------------
# Model wrapper with rope_deltas passthrough (as provided)
# -----------------------------
@dataclass
class TRASEROutput(ModelOutput):
    loss: Optional[torch.FloatTensor] = None
    logits: Optional[torch.FloatTensor] = None
    past_key_values: Optional[List[torch.FloatTensor]] = None
    hidden_states: Optional[Tuple[torch.FloatTensor]] = None
    attentions: Optional[Tuple[torch.FloatTensor]] = None
    rope_deltas: Optional[torch.LongTensor] = None

class TRASER(Qwen2_5_VLForConditionalGeneration):
    def __init__(self, config: Qwen2_5_VLConfig, **kwargs):
        super().__init__(config)
        for k, v in kwargs.items():
            print(f"Keyword arg: {k} = {v}")
            if not hasattr(config, k):
                print(f" - Adding attribute {k} to config with value {v}")
                setattr(config, k, v)
        
        self.config = config
        self._build_perceiver(dtype=config.torch_dtype, attn_impl=config._attn_implementation)
        self.post_init()

    def _build_perceiver(self, dtype: torch.dtype, attn_impl: str) -> None:
        h = int(getattr(self.config, "hidden_size", 2048))
        n_latents = int(getattr(self.config, "temporal_resampler_n_latents", 64))
        depth = int(getattr(self.config, "resampler_depth", 3))

        perceiver_cfg = Idefics2PerceiverConfig(
            hidden_size=h,
            resampler_n_latents=n_latents,
            resampler_depth=depth,
            _attn_implementation=attn_impl,
            torch_dtype=dtype,
        )
        self.perceiver_resampler = Idefics2PerceiverResampler(perceiver_cfg)
        
        if getattr(self.config, "object_resampler", True):
            second_n_latents = int(getattr(self.config, "object_resampler_n_latents", 32))

            second_perceiver_cfg = Idefics2PerceiverConfig(
                hidden_size=h,
                resampler_n_latents=second_n_latents,
                resampler_depth=depth,
                _attn_implementation=attn_impl,
                torch_dtype=dtype,
            )
            self.second_perceiver_resampler = Idefics2PerceiverResampler(second_perceiver_cfg)

    def prepare_inputs_for_generation(
        self,
        input_ids,
        past_key_values=None,
        attention_mask=None,
        inputs_embeds=None,
        cache_position=None,
        position_ids=None,
        use_cache=True,
        pixel_values=None,
        pixel_values_videos=None,
        image_grid_thw=None,
        video_grid_thw=None,
        second_per_grid_ts=None,
        **kwargs,
    ):
        model_inputs = super().prepare_inputs_for_generation(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            cache_position=cache_position,
            position_ids=position_ids,
            pixel_values=pixel_values,
            pixel_values_videos=pixel_values_videos,
            image_grid_thw=image_grid_thw,
            video_grid_thw=video_grid_thw,
            second_per_grid_ts=second_per_grid_ts,
            use_cache=use_cache,
            **kwargs,
        )

        model_inputs["position_ids"] = position_ids
        if cache_position is not None and cache_position[0] != 0:
            model_inputs["pixel_values"] = None
            model_inputs["pixel_values_videos"] = None
            model_inputs["position_ids"] = None
        return model_inputs

    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[List[torch.FloatTensor]] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        cache_position: Optional[torch.LongTensor] = None,
        rope_deltas: Optional[torch.LongTensor] = None,
        **kwargs: Unpack[Any],
    ) -> TRASEROutput:

        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states

        if rope_deltas is not None:
            self.model.rope_deltas = rope_deltas 

        is_prefill = (inputs_embeds is not None) and (
            past_key_values is None or (hasattr(past_key_values, "get_seq_length") and past_key_values.get_seq_length() == 0)
        )

        if is_prefill:
            outputs = self.model.language_model(
                input_ids=None,
                inputs_embeds=inputs_embeds,
                position_ids=position_ids,
                attention_mask=attention_mask,
                past_key_values=past_key_values,
                use_cache=use_cache,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                cache_position=cache_position,
                return_dict=True,
            )
        else:
            inputs_embeds = self.model.get_input_embeddings()(input_ids)
            batch_size, seq_length, _ = inputs_embeds.shape
            delta = (
                (cache_position[0] + self.model.rope_deltas).to(inputs_embeds.device)
                if cache_position is not None
                else 0
            )
            pos = torch.arange(seq_length, device=inputs_embeds.device).view(1, -1).expand(batch_size, -1)
            if cache_position is not None:
                delta = delta.repeat_interleave(max(1, batch_size // delta.shape[0]), dim=0)
            pos = pos.add(delta).unsqueeze(0).expand(3, -1, -1)

            outputs = self.model.language_model(
                input_ids=None,
                position_ids=pos,
                attention_mask=attention_mask,
                past_key_values=past_key_values,
                inputs_embeds=inputs_embeds,
                use_cache=use_cache,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                cache_position=cache_position,
                **kwargs,
            )

        hidden_states = outputs.last_hidden_state
        logits = self.lm_head(hidden_states)

        loss = None
        if labels is not None:
            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)

        return TRASEROutput(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
            rope_deltas=self.model.rope_deltas,
        )



def set_seed(seed: int):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)



def list_video_names(structured_json_root: str, dataset_subset: str = "vidor", meta_data : str = None, eval: bool = False) -> List[str]:
    """List directory names under structured_json_root as video names."""
    if not os.path.isdir(structured_json_root):
        raise FileNotFoundError(f"structured_json_root not found: {structured_json_root}")
    names = [d for d in os.listdir(structured_json_root) if os.path.isdir(os.path.join(structured_json_root, d))]
    if dataset_subset.lower() == "vidor":
        # Filter to only those that look like VIDOR video ids, looks like 0001_xxxxxx....x.json
        names = [n for n in names if re.match(r"^\d{4}_[a-z0-9]+$", n)]
        if eval:
            with open(meta_data, "r") as f:
                meta = json.load(f)
            eval_list = meta['split']['vidor']['val']
            names = [n for n in names if n in eval_list]
    elif dataset_subset.lower() == 'epic_kitchen':
        names = [n for n in names if re.match(r"^P\d{2}_\d{2}$", n)]
        if eval:
            with open(meta_data, "r") as f:
                meta = json.load(f)
            eval_list = meta['split']['epic_kitchen']['val']
            names = [n for n in names if n in eval_list]
    elif dataset_subset.lower() == "ego4d":
        pattern = re.compile(r"^[0-9a-f\-]+(?:_\d+)?$", re.IGNORECASE)
        names = [n for n in names if pattern.match(n)]
        if eval:
            with open(meta_data, "r") as f:
                meta = json.load(f)
            eval_list = meta['split']['ego4d']['val']
            names = [n for n in names if n in eval_list]
    elif dataset_subset.lower() == "all":
        if eval:
            with open(meta_data, "r") as f:
                meta = json.load(f)
            eval_list = []
            for ds in ['vidor', 'epic_kitchen', 'ego4d']:
                eval_list.extend(meta['split'][ds]['val'])
            names = [n for n in names if n in eval_list]
    else:
        raise NotImplementedError("Other dataset support is not implemented.")
    names.sort()
    return names



def available_object_ids(video_struct_dir: str) -> List[int]:
    """Return object ids that have object_{id}.json in the given dir."""
    ids = []
    if not os.path.isdir(video_struct_dir):
        return ids
    for fn in os.listdir(video_struct_dir):
        m = re.match(r"object_(\d+)\.json$", fn)
        if m:
            ids.append(int(m.group(1)))
    ids.sort()
    return ids


def load_mask_data(mask_json_path: str):
    """Load mask data: expected to be List[List[Optional[RLE]]]."""
    if not os.path.isfile(mask_json_path):
        raise FileNotFoundError(mask_json_path)
    with open(mask_json_path, "r") as f:
        data = json.load(f)
    return data


def has_any_mask(mask_data, obj_id: int) -> bool:
    """Check if any frame has a non-empty RLE for this object index."""
    for frame in mask_data:
        if not frame:
            continue
        if obj_id < 0 or obj_id >= len(frame):
            continue
        rle = frame[obj_id]
        if rle:
            # A minimal sanity: counts present and non-empty
            if isinstance(rle, dict) and rle.get("counts"):
                return True
    return False

def build_obj_masks_tensor(
    mask_data,
    obj_ids: List[int],
    sampled_idx: List[int],
    H_rz: int,
    W_rz: int,
    device: torch.device,
) -> Tuple[torch.Tensor, List[int]]:

    O = len(obj_ids)
    N = len(sampled_idx)
    obj_masks = torch.zeros((O, N, H_rz, W_rz), dtype=torch.float32, device=device)

    for o_i, oid in enumerate(obj_ids):
        for n_idx, fidx in enumerate(sampled_idx):
            if fidx < 0 or fidx >= len(mask_data):
                continue
            frame_objs = mask_data[fidx]
            if frame_objs is None or oid < 0 or oid >= len(frame_objs):
                continue
            rle = frame_objs[oid]
            if not rle:
                continue
            m = maskUtils.decode({"size": rle["size"], "counts": rle["counts"]})
            if m.ndim == 3:
                m = m[:, :, 0]


            m_t = torch.from_numpy(m.astype(np.uint8)).unsqueeze(0).unsqueeze(0).float().to(device)
            m_rz = F.interpolate(m_t, size=(H_rz, W_rz), mode="nearest")[0, 0]
            obj_masks[o_i, n_idx] = (m_rz > 0.5).to(torch.float32)

    keep_idx = (obj_masks.view(O, -1).sum(dim=1) > 0).nonzero(as_tuple=False).squeeze(1).tolist()
    if len(keep_idx) == 0:
        raise RuntimeError("All objects have empty masks after aligning to sampled frames.")
    if len(keep_idx) < O:
        obj_masks = obj_masks[keep_idx]

    return obj_masks, keep_idx



# -----------------------------
# Inference core
# -----------------------------

def run_single_video(
    model,
    processor,
    video_path: str,
    mask_path: str,
    video_struct_dir: str,
    out_dir: str,
    device: torch.device,
    *,
    max_objects: int = 40,
    rng: random.Random = random.Random(42),
    spatial_merge_size: int = 2,
    temporal_patch_size: int = 2,
    coverage_thresh: float = 0.7,
    obj_traj_start_id: Optional[int] = None,
    obj_traj_end_id: Optional[int] = None,
    do_sample: bool = False,
    temperature: float = 0.7,
    top_p: float = 0.9,
    max_new_tokens: int = 512,
    repetition_penalty: float = 1.05,
    system_prompt: Optional[str] = None,
    messages_text: Optional[List[Dict]] = None,
    temporal_window_length: float = 4.0,
    training_fps: float = 1.0,
) -> Dict:
    """
    Process a single video and return a dict of results. Also writes artifacts to disk.
    """
    os.makedirs(out_dir, exist_ok=True)

    # 0) Check resources
    if not os.path.isfile(video_path):
        raise FileNotFoundError(f"Video file not found: {video_path}")
    if not os.path.isfile(mask_path):
        raise FileNotFoundError(f"Mask json not found: {mask_path}")
    if not os.path.isdir(video_struct_dir):
        raise FileNotFoundError(f"struct json dir not found: {video_struct_dir}")

    # 1) Determine eligible object ids (existence + has any mask), then sample up to max_objects
    mask_data = load_mask_data(mask_path)
    all_ids = available_object_ids(video_struct_dir)
    eligible = [oid for oid in all_ids if has_any_mask(mask_data, oid)]
    if len(eligible) == 0:
        raise RuntimeError(f"No eligible objects with masks for video dir: {video_struct_dir}")
    if len(eligible) > max_objects:
        rng.shuffle(eligible)
        selected_obj_ids = sorted(eligible[:max_objects])
    else:
        selected_obj_ids = sorted(eligible)

    # 2) Prepare processor inputs
    # Build messages and prompt
    if system_prompt is None:
        system_prompt = (
            "You are a helpful assistant."
        )

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": [{"type": "video", "video": video_path}]},
    ] if messages_text is None else [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content":[
            {"type": "text", "text": messages_text},
            {"type": "video", "video": video_path}
        ]}
    ]
    print("Messages:", messages)

    prompt_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    
    image_inputs, video_inputs, selected_frame_fps, selected_frame_idx = process_vision_info(messages, return_video_kwargs = True)

    print("selected_frame_fps:", selected_frame_fps)
    proc_inputs = processor(
        text=[prompt_text],
        images=image_inputs,
        videos=video_inputs,
        padding=True,
        return_tensors="pt",
        fps=1,
    ).to(model.device)
    
    
    # proc_inputs = processor(text=[prompt_text], videos=[video_path], return_tensors="pt")

    # Move to device
    input_ids = proc_inputs["input_ids"].to(device)
    attention_mask = proc_inputs["attention_mask"].to(device)
    pixel_values_videos = proc_inputs.get("pixel_values_videos", None)
    # if pixel_values_videos is not None:
    #     pixel_values_videos = pixel_values_videos.to(device, dtype=model.dtype)

    video_grid_thw = proc_inputs.get("video_grid_thw", None)
    if video_grid_thw is None:
        raise RuntimeError("processor did not return 'video_grid_thw'")
    # Normalize to tensor of shape [B, 3] or [3]
    if isinstance(video_grid_thw, (list, tuple)):
        video_grid_thw = [torch.as_tensor(v, device=device) for v in video_grid_thw]
        video_grid_thw = torch.stack(video_grid_thw, dim=0)
    else:
        video_grid_thw = video_grid_thw.to(device)
    # For single video we expect shape [1, 3]
    if video_grid_thw.dim() == 1:
        video_grid = video_grid_thw
    else:
        video_grid = video_grid_thw[0]
    T, H_patch, W_patch = int(video_grid[0].item()), int(video_grid[1].item()), int(video_grid[2].item())

    sec_per_window = torch.arange(0, T) * ((1 / int(training_fps) * 2))
    per_timestamp_idx_batch = [[v.item() for v in sec_per_window]]


    patch_size = getattr(getattr(processor, "video_processor", None), "patch_size", 14)
    H_rz, W_rz = H_patch * patch_size, W_patch * patch_size

    # 3) Build obj_masks for selected objects
    sampled_idx = selected_frame_idx[0] if isinstance(selected_frame_idx, list) and len(selected_frame_idx) > 0 and isinstance(selected_frame_idx[0], list) else selected_frame_idx
    obj_masks, keep_idx= build_obj_masks_tensor(mask_data, selected_obj_ids, sampled_idx, H_rz, W_rz, device=device)
    selected_obj_ids = [selected_obj_ids[j] for j in keep_idx]
    
    # 4) Select tokens for these objects
    per_union_idx, per_obj_idx, _per_obj_cover = select_tokens(
        obj_masks=obj_masks,
        grid_thw=(T, H_patch, W_patch),
        patch_size=patch_size,
        spatial_merge_size=spatial_merge_size,
        temporal_patch_size=temporal_patch_size,
        coverage_thresh=coverage_thresh,
        device=device,
    )

    # 5) Prepare insertion (we only need per_obj_idx for this sample)
    per_obj_idx_batch = [per_obj_idx]  # B=1 list of list-of-tensors
    text_token_ids_per_sample = None
    label_template = "Object {i}: "

    text_token_ids_per_sample = []
    max_len = 0

    for per_obj_idx in per_obj_idx_batch:
        O = len(per_obj_idx)
        additional_texts = [label_template.format(i=(k + 1)) for k in range(O)]
        if len(additional_texts) == 0:
            text_token_ids_per_sample.append([])
            continue

        enc = processor.tokenizer(
            additional_texts,
            add_special_tokens=False,
            return_attention_mask=False,
            return_token_type_ids=False,
        )["input_ids"]

        # per_sample_ids = [torch.tensor(x, dtype=torch.long, device=input_ids.device) for x in enc]
        per_sample_ids = [torch.tensor(x, dtype=torch.long) for x in enc]
        text_token_ids_per_sample.append(per_sample_ids)

    grids_per_temporal_window = int(temporal_window_length / (1.0 / training_fps)) / 2  # e.g., 4s window @ 1fps / merge_size → 2 grids
    timestamp_token_ids_per_batch = []
    grids_per_temporal_window_per_batch = []

    assert processor.tokenizer is not None
    for per_timestamp_idx in per_timestamp_idx_batch:
        temporal_window_num = math.ceil(len(per_timestamp_idx) / grids_per_temporal_window)
        temporal_text_list = []
        for w_id in range(temporal_window_num):
            start_time = w_id * temporal_window_length
            end_time = start_time + temporal_window_length
            temporal_text_list.append(f"<{int(start_time)} - {int(end_time)} sec>")
        enc = processor.tokenizer(
            temporal_text_list,
            add_special_tokens=False,
            return_attention_mask=False,
            return_token_type_ids=False,
        )["input_ids"]
        timestamp_token_ids_per_batch.append([torch.tensor(x) for x in enc])
        grids_per_temporal_window_per_batch.append(int(grids_per_temporal_window))



    with torch.no_grad():
        new_emb, new_pid, new_mask, rope_deltas, cache_pos, new_input_ids, new_labels = rearrange_token(
            model=model,
            input_ids=input_ids,
            attention_mask=attention_mask,
            pixel_values_videos=pixel_values_videos,
            video_grid_thw=video_grid_thw,
            image_grid_thw=None,
            pixel_values=None,
            second_per_grid_ts=None,
            obj_token_indices_per_sample=per_obj_idx_batch,
            obj_traj_start_id=obj_traj_start_id,
            obj_traj_end_id=obj_traj_end_id,
            use_resampler=True,
            text_token_ids_per_sample=text_token_ids_per_sample,
            timestamp_token_ids_per_batch=timestamp_token_ids_per_batch,
            grids_per_temporal_window_per_batch=grids_per_temporal_window_per_batch,
            labels=None,
            
        )
        new_mask=new_mask.to(torch.long)
        # 6) Generate
        gen_out = model.generate(
            inputs_embeds=new_emb,
            position_ids=new_pid,
            attention_mask=new_mask,
            rope_deltas=rope_deltas,
            max_new_tokens=max_new_tokens,
            do_sample=do_sample,
            use_cache=True,
            temperature=temperature if do_sample else None,
            top_p=top_p if do_sample else None,
            repetition_penalty=repetition_penalty,
            return_dict_in_generate=True,
        )

    sequences = gen_out.sequences  # [1, L_in + L_gen]
    # Only decode generated part
    in_len = new_emb.shape[1]
    gen_tokens = sequences[0]
    decoded = processor.tokenizer.decode(gen_tokens, skip_special_tokens=True)

    # 7) Write artifacts
    video_name = os.path.splitext(os.path.basename(video_path))[0]
    out_txt = os.path.join(out_dir, f"{video_name}_gen.txt")
    out_meta = os.path.join(out_dir, f"{video_name}_meta.json")

    with open(out_txt, "w", encoding="utf-8") as f:
        f.write(decoded.strip())

    meta = {
        "video_name": video_name,
        "video_path": video_path,
        "mask_path": mask_path,
        "structured_json_dir": video_struct_dir,
        "selected_object_ids": selected_obj_ids,
        "T_H_W": [T, H_patch, W_patch],
        "patch_size": patch_size,
        "spatial_merge_size": spatial_merge_size,
        "temporal_patch_size": temporal_patch_size,
        "coverage_thresh": coverage_thresh,
        "do_sample": do_sample,
        "max_new_tokens": max_new_tokens,
        "per_obj_idx_len": [int(x.numel()) for x in per_obj_idx]
    }
    with open(out_meta, "w", encoding="utf-8") as f:
        json.dump(meta, f, ensure_ascii=False, indent=2)

    return {
        "decoded": decoded,
        "meta": meta,
        "out_txt": out_txt,
        "out_meta": out_meta,
        "per_obj_idx_len": [int(x.numel()) for x in per_obj_idx],
    }


# -----------------------------
# CLI
# -----------------------------

def main():
    parser = argparse.ArgumentParser(description="Inference for PVSG/VIDOR with token selection & insertion.")
    parser.add_argument("--model_path", type=str, required=True, help="Path to finetuned Qwen2.5-VL checkpoint.")
    parser.add_argument("--structured_json_root", type=str, required=False, help="Root dir of structured_json/{video_name}/",default="/weka-train/royg/pvsg/object_descriptions")
    parser.add_argument("--mask_root", type=str, required=False, help="Root dir of masks, with {video}_rle.json files.", default = "/weka-train/royg/pvsg/pvsg_rle_json")
    parser.add_argument("--video_root", type=str, required=False, help="Root dir of raw videos, {video}.mp4",default = "/weka-train/jamesp/data/PVSG_dataset/vidor/videos")
    parser.add_argument("--meta_data", type=str, required=False, help="Path of meta data,", default="/weka-train/jamesp/data/PVSG_dataset/pvsg.json")
    parser.add_argument("--eval", type=bool, required=False, help="Whether to run evaluation splits.", default=True)
    
    parser.add_argument("--out_dir", type=str, required=False, help="Output directory to save generations + metadata.", default="/weka/royg/vsg_train/Qwen2.5-VL/pvsg_resampler_output")
    parser.add_argument("--dataset_subset", type=str, default="vidor", help="Dataset subset to evaluate.")

    parser.add_argument("--temporal_window_length", type=float, default=4.0, help="Temporal window length in seconds for timestamp text anchors.")
    parser.add_argument("--training_fps", type=float, default=1.0, help="Frames per second for training.")
    
    parser.add_argument("--max_objects", type=int, default=40, help="Max objects to sample per video (<=40).")
    parser.add_argument("--seed", type=int, default=42, help="Random seed for sampling.")
    parser.add_argument("--dtype", type=str, default="bfloat16", choices=["float16", "bfloat16", "float32"], help="Model dtype.")
    parser.add_argument("--device", type=str, default="cuda", help="Device like 'cuda' or 'cuda:0' or 'cpu'.")
    parser.add_argument("--limit_videos", type=int, default=None, help="Optional limit on number of videos.")
    parser.add_argument("--start_from", type=int, default=0, help="Start index offset for listing videos.")
    parser.add_argument("--coverage_thresh", type=float, default=0.5)
    parser.add_argument("--spatial_merge_size", type=int, default=2)
    parser.add_argument("--temporal_patch_size", type=int, default=2)
    parser.add_argument("--obj_traj_start_id", type=int, default=151665)
    parser.add_argument("--obj_traj_end_id", type=int, default=151666)
    parser.add_argument("--max_new_tokens", type=int, default=16384)
    parser.add_argument("--do_sample", action="store_true", default=True)
    parser.add_argument("--temperature", type=float, default=1e-6)
    parser.add_argument("--top_p", type=float, default=0.9)
    parser.add_argument("--repetition_penalty", type=float, default=1.05)
    args = parser.parse_args()

    # Device & dtype
    device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu")
    dtype_map = {"float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32}
    dt = dtype_map[args.dtype]
        
    # Enumerate videos by folders under structured_json_root
    if "," in args.dataset_subset:
        dataset_subsets = args.dataset_subset.split(",")
        video_names = []
        for ds in dataset_subsets:
            video_names += list_video_names(args.structured_json_root, dataset_subset=ds, meta_data=args.meta_data, eval=args.eval)
        video_names = sorted(list(set(video_names)))
    else:
        video_names = list_video_names(args.structured_json_root, dataset_subset=args.dataset_subset, meta_data=args.meta_data, eval=args.eval)
    print(f"Total videos: {len(video_names)}")
    
    if args.start_from > 0:
        video_names = video_names[args.start_from:]
    if args.limit_videos is not None:
        video_names = video_names[: args.limit_videos]
        

    set_seed(args.seed)

    processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct")
    model = TRASER.from_pretrained(
        args.model_path, torch_dtype=dt, device_map=None
    ).to(device)
    tokenizer = AutoTokenizer.from_pretrained(args.model_path)
    processor.tokenizer = tokenizer


    rng = random.Random(args.seed)

    os.makedirs(args.out_dir, exist_ok=True)
    args.out_dir = os.path.join(args.out_dir, os.path.basename(os.path.dirname(args.model_path)), os.path.basename(args.model_path))

    os.makedirs(args.out_dir, exist_ok=True)
    

    messages_text = "Output the video Scene Graph from the video and object trajectories:\n"

    
    index_path = os.path.join(args.out_dir, "index.jsonl")
    with open(index_path, "a", encoding="utf-8") as index_f:
        print(">>> writing index to:", index_path)
        for vi, video_name in enumerate(video_names):
            # try:
            if os.path.exists(os.path.join(args.out_dir, f"{video_name}_gen.txt")):
                print(f"[SKIP] {video_name}: already processed")
                continue
            video_struct_dir = os.path.join(args.structured_json_root, video_name)
            mask_path = os.path.join(args.mask_root, f"{video_name}_rle.json")
            # video file could be nested; user said direct: {video_root}/{video_name}.mp4
            video_path = find_video_path(args.video_root, video_name)

            result = run_single_video(
                model=model,
                processor=processor,
                video_path=video_path,
                mask_path=mask_path,
                video_struct_dir=video_struct_dir,
                out_dir=args.out_dir,
                device=device,
                max_objects=args.max_objects,
                rng=rng,
                spatial_merge_size=args.spatial_merge_size,
                temporal_patch_size=args.temporal_patch_size,
                coverage_thresh=args.coverage_thresh,
                obj_traj_start_id=args.obj_traj_start_id,
                obj_traj_end_id=args.obj_traj_end_id,
                do_sample=args.do_sample,
                temperature=args.temperature,
                top_p=args.top_p,
                max_new_tokens=args.max_new_tokens,
                repetition_penalty=args.repetition_penalty,
                messages_text=messages_text,
                temporal_window_length=args.temporal_window_length,
                training_fps=args.training_fps,
            )

            # Append to index
            rec = {
                "video_name": video_name,
                "out_txt": result["out_txt"],
                "out_meta": result["out_meta"],
                "selected_object_count": len(result["meta"]["selected_object_ids"]),
                "per_obj_selected_token_counts": result["per_obj_idx_len"],
            }
            index_f.write(json.dumps(rec, ensure_ascii=False) + "\n")
            index_f.flush()


            print(f"[{vi+1}/{len(video_names)}] done: {video_name} -> {result['out_txt']}")


if __name__ == "__main__":
    main()