File size: 6,515 Bytes
5a13ac8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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

# --- configuration ---------------------------------------------------------
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 setup --------------------------------------------------------
logging.basicConfig(filename=LOG_FILE, filemode="w", level=logging.WARNING)

# --- helper functions ------------------------------------------------------
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 ""

# --- load model & processor with multi-GPU --------------------------------
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,3"  # Use GPU 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"
)

# --- main evaluation loop --------------------------------------------------
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}) # 遇到新key,自动初始化为0

total_qa = 0

# Outer evaluation loop
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"]

        # Build prompt without <image> tag
        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:"
        )

        # Build messages with image and text
        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() # check the assistant only, not the system message

        pred = extract_letter(assistant_response) # only take the last letter in the "answer" so that the options won't influence the answer extraction

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

# --- write per-dimension accuracy to CSV -----------------------------------
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%}"])

# --- write per-scenario accuracy to CSV ------------------------------------
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}")