mio / miomio.py
kieranleen's picture
Upload miomio.py with huggingface_hub
5a13ac8 verified
"""
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}")