File size: 9,427 Bytes
286711d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import torch
import torch.multiprocessing as mp
import argparse
import numpy as np
import random
from collections import defaultdict
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
from tqdm import tqdm
import threading
import time

CONFIG = {
    "MODEL_PATH": "path/to/Qwen3-VL-8B-Instruct",
    "TARGET_JSON_PATH": "path/to/test.json",
    "max_pixels": 512**2,
    "DEFAULT_GPUS": 8,
    "max_tokens": 128,
}

def load_model_and_processor(model_path, device):
    model = Qwen3VLForConditionalGeneration.from_pretrained(
        model_path,
        dtype="auto"
    ).to(device)
    processor = AutoProcessor.from_pretrained(model_path)
    return model, processor

def build_interleaved_messages(qa_item):
    content_list = []
    videos_data = qa_item.get("videos", [])
    question_text = qa_item.get("question", "")

    if isinstance(videos_data, list):
        num_video_placeholders = question_text.count('<video>')
        
        if num_video_placeholders == len(videos_data):
            text_parts = question_text.split('<video>')
            for i, video_data in enumerate(videos_data):
                if text_parts[i]:
                    content_list.append({"type": "text", "text": text_parts[i]})
                content_list.append(
                    {
                        "type": "video", 
                        "video": video_data['video'],
                        "sample_fps": video_data['sample_fps'],
                        "max_pixels":CONFIG["max_pixels"],
                        "min_pixels":128 ** 2
                    })
            if text_parts[-1]:
                content_list.append({"type": "text", "text": text_parts[-1]})
        else:
            print("build_interleaved_messages_error")
        
    return [{
            "content": "Based on this video, provide the answer directly.",
            "role": "system"
        },
        {
            "role": "user", 
            "content": content_list
        }]


def calculate_score(prediction, ground_truth, task_type):
    if task_type == "Jigsaw":
        return 1.0 if str(prediction).strip() == str(ground_truth).strip() else 0.0

    elif task_type == "Counting":
        try:
            gt_parts = [p.strip() for p in str(ground_truth).split(',')]
            pred_parts = [p.strip() for p in str(prediction).split(',')]
            
            if len(gt_parts) != 3:
                print(f"Warning: Ground truth for Counting task '{ground_truth}' does not have 3 parts.")
                return 0.0

            total_score = 0.0

            for i in range(3):
                if i < len(pred_parts) and pred_parts[i] == gt_parts[i]:
                    total_score += 1.0
            
            return total_score / 3.0
        except Exception as e:
            print(f"Error parsing Counting prediction: {e}")
            return 0.0

    elif task_type == "Grounding": 
        try:
            gt_start, gt_end = map(float, str(ground_truth).split('-'))
            pred_start, pred_end = map(float, str(prediction).split('-'))

            inter_start = max(gt_start, pred_start)
            inter_end = min(gt_end, pred_end)

            intersection_area = max(0, inter_end - inter_start)

            gt_area = gt_end - gt_start
            pred_area = pred_end - pred_start
            union_area = gt_area + pred_area - intersection_area

            if union_area == 0:
                return 1.0 if intersection_area > 0 else 0.0
            
            iou = intersection_area / union_area
            return iou
        except (ValueError, IndexError) as e:
            return 0.0
            

def process_single_item(qa_item, model, processor):
    correct_answer = qa_item.get("answer")
    ability_type = qa_item.get("ability_type")
    task_type = qa_item.get("task_type")
    subset = qa_item.get("subset")

    try:
        messages = build_interleaved_messages(qa_item)
        text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
        images, videos, video_kwargs = process_vision_info(messages, image_patch_size=16, return_video_kwargs=True, return_video_metadata=True)
        if videos is not None:
            videos, video_metadatas = zip(*videos)
            videos, video_metadatas = list(videos), list(video_metadatas)
        else:
            video_metadatas = None

        inputs = processor(text=text, images=images, videos=videos, video_metadata=video_metadatas, return_tensors="pt", do_resize=False, **video_kwargs)
        inputs = inputs.to(model.device)
        
        generated_ids = model.generate(**inputs, max_new_tokens=CONFIG["max_tokens"], do_sample=False)
        generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
        output_text = processor.batch_decode(
            generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
        )[0]
        predicted_answer = output_text 
        
        score = calculate_score(predicted_answer, correct_answer, task_type)
        
        print(f"Task: {task_type} | Predicted: {predicted_answer} | Correct: {correct_answer} | Score: {score:.2f}")

        return ("success", score, ability_type, task_type, subset)

    except Exception as e:
        print(f"Error processing item for subset {subset}: {e}")
        return ("error", 0.0, ability_type, task_type, subset)


def aggregate_and_print_results(all_results, total_dataset_size):
    if not all_results:
        print("No results to aggregate.")
        return

    scores_by_ability = defaultdict(list)
    scores_by_task = defaultdict(list)
    scores_by_subset = defaultdict(list) 
    error_count = 0
    success_count = 0

    for result in all_results:
        status, score, ability, task, subset = result
        scores_by_ability[ability].append(score)
        scores_by_task[task].append(score)
        scores_by_subset[subset].append(score) 

        if status == "success":
            success_count += 1
        else:
            error_count += 1

    def print_report(title, score_dict):
        print(f"--- {title.upper()} AVERAGE SCORES ---")
        if not score_dict:
            print("No data available.")
            return
            
        total_scores = []
        for name, scores in sorted(score_dict.items()):
            avg_score = np.mean(scores) if scores else 0
            total_scores.extend(scores)
            print(f"{name:<25} | Average Score: {avg_score:.4f} (N={len(scores)})")
        
        overall_avg = np.mean(total_scores) if total_scores else 0
        print("-" * 50)
        print(f"{'Overall ' + title:<25} | Average Score: {overall_avg:.4f} (N={len(total_scores)})")
        print("-" * 50)


    print("\n" + "="*50)
    print(" " * 16 + "EVALUATION RESULTS")
    print("="*50)
    print(f"Model Path: {CONFIG['MODEL_PATH']}")
    print(f"Total Items in Dataset: {total_dataset_size}")
    print(f"Successfully Processed: {success_count}")
    print(f"Processing Errors: {error_count}\n")

    print_report("Ability", scores_by_ability)
    print("")
    print_report("Task", scores_by_task)
    print("")
    print_report("Subset", scores_by_subset) 
    print("="*50)

def worker(rank, task_queue, results_list):
    os.environ["CUDA_VISIBLE_DEVICES"] = str(rank)
    device = torch.device(f"cuda:{str(rank)}")

    model, processor = load_model_and_processor(CONFIG["MODEL_PATH"], device)

    while True:
        try:
            qa_item = task_queue.get_nowait()
        except Exception:
            break 

        result = process_single_item(qa_item, model, processor)
        results_list.append(result)

def progress_monitor(results_list, total_size, stop_event):
    with tqdm(total=total_size, desc="Processing Items", unit="item") as pbar:
        while not stop_event.is_set():
            current_count = len(results_list)
            pbar.update(current_count - pbar.n)
            if current_count >= total_size:
                break
            time.sleep(1)
        pbar.update(total_size - pbar.n)


def main():
    world_size = CONFIG['DEFAULT_GPUS']

    try:
        with open(CONFIG["TARGET_JSON_PATH"], 'r', encoding='utf-8') as f:
            full_dataset = json.load(f)
        total_dataset_size = len(full_dataset)
        print(f"Successfully loaded {total_dataset_size} items from {CONFIG['TARGET_JSON_PATH']}.")
    except Exception as e:
        print(f"Fatal: Error loading dataset. {e}")
        return

    random.shuffle(full_dataset)

    with mp.Manager() as manager:
        task_queue = manager.Queue()
        for item in full_dataset:
            task_queue.put(item)

        results_list = manager.list()

        stop_event = threading.Event()
        progress_thread = threading.Thread(
            target=progress_monitor,
            args=(results_list, total_dataset_size, stop_event)
        )
        progress_thread.start()

        mp.spawn(worker,
                 args=(task_queue, results_list),
                 nprocs=world_size,
                 join=True)

        stop_event.set()
        progress_thread.join()

        final_results = list(results_list)

    aggregate_and_print_results(final_results, total_dataset_size)


if __name__ == "__main__":
    mp.set_start_method("spawn", force=True)
    main()