| 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() |