| | """ |
| | Evaluate Qwen2.5-VL-7B on MCQA-style fire dataset using multiple GPUs for model loading. |
| | """ |
| |
|
| | import json |
| | import re |
| | import torch |
| | import os |
| | import csv |
| | from PIL import Image |
| | from tqdm import tqdm |
| | from transformers import AutoProcessor, AutoModelForVision2Seq |
| | import logging |
| | from collections import defaultdict |
| | from qwen_vl_utils import process_vision_info |
| |
|
| | |
| | MODEL_ID = "Qwen/Qwen2.5-VL-7B-Instruct" |
| | DATA_FILE = "/home/muzammal/Projects/Qwen-2.5-VL/qa_dataset_concat_cleaned.json" |
| | IMAGE_ROOT = "/home/muzammal/Projects/Qwen-2.5-VL/UniFire_11k/UniFire" |
| | MAX_TOKENS = 12 |
| | LOG_FILE = "missing_images_qwen.log" |
| | CSV_RESULT_DIM = "vqa_qwen_accuracy_by_dimension.csv" |
| | CSV_RESULT_SCEN = "vqa_qwen_accuracy_by_scenario.csv" |
| |
|
| | |
| | logging.basicConfig(filename=LOG_FILE, filemode="w", level=logging.WARNING) |
| |
|
| | |
| | def build_prompt(question, options): |
| | return ( |
| | "<|image|>\n" |
| | "You are given the picture of fire. Answer with the option letter (A, B, C, or D) only from the given choices directly.\n\n" |
| | f"Question: {question}\n" |
| | f"{options[0]}\n" |
| | f"{options[1]}\n" |
| | f"{options[2]}\n" |
| | f"{options[3]}\n\n" |
| | "Answer:" |
| | ) |
| |
|
| | def extract_letter(text): |
| | m = re.search(r"\b([A-D])\b", text, re.IGNORECASE) |
| | return m.group(1).upper() if m else "" |
| |
|
| | |
| | os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,3" |
| |
|
| | processor = AutoProcessor.from_pretrained(MODEL_ID) |
| | model = AutoModelForVision2Seq.from_pretrained( |
| | MODEL_ID, |
| | torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, |
| | device_map="auto" |
| | ) |
| |
|
| | |
| | with open(DATA_FILE) as f: |
| | dataset = json.load(f) |
| |
|
| | correct = 0 |
| | results = [] |
| | missing = [] |
| |
|
| | |
| | dimension_stats = defaultdict(lambda: {"correct": 0, "total": 0}) |
| | scenario_stats = defaultdict(lambda: {"correct": 0, "total": 0}) |
| |
|
| | total_qa = 0 |
| |
|
| | |
| | for scene_path, scene in tqdm(dataset.items(), desc="Evaluating MCQA VQA"): |
| | print(f"Processing scene: {scene_path}") |
| | image_path = os.path.join(IMAGE_ROOT, scene_path) |
| | print(f"Image path: {image_path}") |
| |
|
| | try: |
| | image = Image.open(image_path).convert("RGB") |
| | except Exception as e: |
| | logging.warning(f"Missing or unreadable image: {scene_path} - {e}") |
| | missing.append(scene_path) |
| | continue |
| |
|
| | scenario = scene.get("scenario", "Unknown") |
| |
|
| | for i, qa in enumerate(scene.get("QA_pairs", [])): |
| | qid = f"{scene_path}_{i}" |
| | options = qa["options"] |
| |
|
| | |
| | text_prompt = ( |
| | "You are given the picture of fire. Answer with the option letter (A, B, C, or D) only from the given choices directly.\n\n" |
| | f"Question: {qa['question']}\n" |
| | f"{options[0]}\n{options[1]}\n{options[2]}\n{options[3]}\n\nAnswer:" |
| | ) |
| |
|
| | |
| | messages = [{ |
| | "role": "user", |
| | "content": [ |
| | {"type": "image", "image": image}, |
| | {"type": "text", "text": text_prompt}, |
| | ] |
| | }] |
| |
|
| | chat_prompt = processor.apply_chat_template( |
| | messages, tokenize=False, add_generation_prompt=True |
| | ) |
| | image_inputs, video_inputs = process_vision_info(messages) |
| |
|
| | inputs = processor( |
| | text=[chat_prompt], |
| | images=image_inputs, |
| | videos=video_inputs, |
| | return_tensors="pt" |
| | ).to(model.device) |
| |
|
| | output = model.generate(**inputs, max_new_tokens=MAX_TOKENS) |
| | decoded = processor.batch_decode(output, skip_special_tokens=True)[0] |
| | assistant_response = decoded.split("assistant\n")[-1].strip() |
| |
|
| | pred = extract_letter(assistant_response) |
| |
|
| | correct_option = qa["answer"][0].upper() |
| | |
| | print("="*50) |
| | print("[Full decoded output]\n", decoded) |
| | print("[Assistant-only response]\n", assistant_response) |
| | print("[Extracted Letter]:", pred) |
| | print("[Ground Truth]:", correct_option) |
| | print("="*50) |
| |
|
| |
|
| | is_correct = pred == correct_option |
| | correct += is_correct |
| | total_qa += 1 |
| |
|
| | question_text = qa["question"] |
| | dimension_stats[question_text]["total"] += 1 |
| | scenario_stats[scenario]["total"] += 1 |
| | if is_correct: |
| | dimension_stats[question_text]["correct"] += 1 |
| | scenario_stats[scenario]["correct"] += 1 |
| |
|
| | results.append({ |
| | "id": qid, |
| | "question": question_text, |
| | "scenario": scenario, |
| | "gt": correct_option, |
| | "pred": pred, |
| | "is_correct": is_correct |
| | }) |
| |
|
| |
|
| | accuracy = correct / total_qa if total_qa > 0 else 0 |
| | print(f"\nEvaluated {total_qa} QA pairs.") |
| | print(f"Missing images: {len(missing)} logged in {LOG_FILE}") |
| | print(f"Overall accuracy: {accuracy:.2%}\n") |
| |
|
| | |
| | with open(CSV_RESULT_DIM, mode="w", newline="", encoding="utf-8") as f: |
| | writer = csv.writer(f) |
| | writer.writerow(["Question Dimension", "Correct", "Total", "Accuracy"]) |
| | for question, stats in dimension_stats.items(): |
| | acc = stats["correct"] / stats["total"] if stats["total"] > 0 else 0 |
| | writer.writerow([question, stats["correct"], stats["total"], f"{acc:.2%}"]) |
| |
|
| | |
| | with open(CSV_RESULT_SCEN, mode="w", newline="", encoding="utf-8") as f: |
| | writer = csv.writer(f) |
| | writer.writerow(["Fire Scenario", "Correct", "Total", "Accuracy"]) |
| | for scenario, stats in scenario_stats.items(): |
| | acc = stats["correct"] / stats["total"] if stats["total"] > 0 else 0 |
| | writer.writerow([scenario, stats["correct"], stats["total"], f"{acc:.2%}"]) |
| |
|
| | print(f"Per-dimension accuracy written to {CSV_RESULT_DIM}") |
| | print(f"Per-scenario accuracy written to {CSV_RESULT_SCEN}") |