File size: 15,699 Bytes
2e208c6 | 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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | import gc
import re
import os
import json
from typing import Dict, Iterator
import torch
import pandas as pd
from datasets import load_dataset
from multiprocessing import Pool
from tqdm import tqdm
from PIL import Image
from transformers import AutoTokenizer
from llava.mm_utils import process_images, tokenizer_image_token
from llava.model.builder import load_pretrained_model # 新增:使用 builder 加载模型
# ============ 本地 LLaVA 模型路径与标识 ============
MODEL_PATH = "/workspace/models/llava-plus-fin-kline-v1.5-7b-full"
MODEL_TAG = "llava_plus_fin_kline_v1_5_7b_full" # 只用于输出文件名
# ============ FinMME 提示模版(保持与官方一致) ============
INSTRUCTIONS = {
'single_choice': (
"Please answer this single choice question about the image. "
"The caption of the image is {verified_caption}. "
"The related sentences are {related_sentences}.\n"
"Please answer the question directly. The answer MUST be of the following format: "
"'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem "
"(the single letter of the correct answer, A, B, C, D, etc.)."
),
'multiple_choice': (
"Please answer this multiple choice question about the image. "
"The caption of the image is {verified_caption}. "
"The related sentences are {related_sentences}.\n"
"Please answer the question directly. The answer MUST be of the following format: "
"'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem "
"(the letter(s) of the correct answer(s), split by ',')."
),
'numerical': (
"Please answer this numerical question about the image. "
"The unit of the answer is {unit}. "
"The caption of the image is {verified_caption}. "
"The related sentences are {related_sentences}.\n"
"Please answer the question directly. The answer MUST be of the following format: "
"'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem "
"(digit number only, without unit or any other text)."
),
}
# ============ 本地 LLaVA 封装(单进程内全局加载一次) ============
print(f"[LLaVA] loading model from {MODEL_PATH} ...")
# 使用官方 builder 一次性加载 tokenizer, model, image_processor
_llava_tokenizer, _llava_model, _image_processor, _ = load_pretrained_model(
model_path=MODEL_PATH,
model_base=None, # fin-kline 为全参数权重
model_name="llava", # LLaVA / LLaVA-Plus 系列用这个
)
_llava_model = _llava_model.cuda().eval()
print("[LLaVA] model loaded.")
# ============ 推理日志记录 ============
INFERENCE_LOG_FILE = "/workspace/code/FinMME/inference_log.txt"
LOG_INFERENCE = True # 设为 False 关闭日志
def log_inference(message: str):
"""记录推理过程到文件"""
if LOG_INFERENCE:
with open(INFERENCE_LOG_FILE, "a", encoding="utf-8") as f:
f.write(message + "\n")
def llava_answer(prompt: str, image: Image.Image | None, max_new_tokens: int = 256, idx: int = -1) -> str:
"""
使用本地 LLaVA 模型回答一个问题(0/1 张图)。
"""
log_inference(f"\n{'='*60}")
log_inference(f"[INFERENCE] Sample idx={idx}")
log_inference(f"{'='*60}")
# ===== 图像处理 =====
log_inference(f"\n[IMAGE PROCESSING]")
if image is not None:
log_inference(f" - Image provided: YES")
log_inference(f" - Original size: {image.size} (W x H)")
log_inference(f" - Mode: {image.mode}")
img_tensor = process_images([image], _image_processor, _llava_model.config)
img_tensor = img_tensor.to(_llava_model.device, dtype=torch.float16)
log_inference(f" - Tensor shape: {img_tensor.shape}")
log_inference(f" - Tensor dtype: {img_tensor.dtype}")
log_inference(f" - Tensor device: {img_tensor.device}")
log_inference(f" - Tensor min/max: {img_tensor.min().item():.4f} / {img_tensor.max().item():.4f}")
conv = "<image>\n" + prompt
else:
log_inference(f" - Image provided: NO")
img_tensor = None
conv = prompt
# ===== 文字处理 =====
log_inference(f"\n[TEXT PROCESSING]")
log_inference(f" - Prompt length: {len(prompt)} chars")
log_inference(f" - Prompt preview: {prompt[:200]}...")
log_inference(f" - Has <image> token: {'<image>' in conv}")
input_ids = tokenizer_image_token(
conv, _llava_tokenizer, return_tensors="pt"
).unsqueeze(0).to(_llava_model.device)
log_inference(f" - Input IDs shape: {input_ids.shape}")
log_inference(f" - Input IDs device: {input_ids.device}")
# ===== 模型推理 =====
log_inference(f"\n[MODEL INFERENCE]")
log_inference(f" - max_new_tokens: {max_new_tokens}")
log_inference(f" - images tensor: {'YES' if img_tensor is not None else 'NO'}")
out_ids = _llava_model.generate(
input_ids,
images=img_tensor,
max_new_tokens=max_new_tokens,
do_sample=False,
temperature=0.0,
)
vocab_size = _llava_tokenizer.vocab_size
out_ids = out_ids.clamp_(0, vocab_size - 1)
text = _llava_tokenizer.decode(out_ids[0], skip_special_tokens=True).strip()
# ===== 输出记录 =====
log_inference(f"\n[MODEL OUTPUT]")
log_inference(f" - Output IDs shape: {out_ids.shape}")
log_inference(f" - Output length: {len(text)} chars")
log_inference(f" - Output text:\n{text}")
log_inference(f"\n{'='*60}\n")
return text
# ============ 工具函数:解析答案 & 计算正确性 ============
import re
def extract_result(res):
"""从末尾开始匹配,优先取最后一个 Answer: X"""
if not res:
return ''
# 找所有匹配,取最后一个(模型真正的答案在末尾)
matches = re.findall(r"(?i)Answer\s*:\s*([^\s\n'\"]+)", res)
if matches:
result = matches[-1]
# 过滤掉模板占位符 $ANSWER
if result.upper().replace('$', '') == 'ANSWER':
# 如果最后一个是占位符,尝试倒数第二个
if len(matches) > 1:
result = matches[-2]
else:
result = ''
return result.rstrip('.,')
return ''
def normalize_response(resp: str) -> str:
return (
resp.replace("**", "")
.replace(":", "")
.replace("$\\boxed{", "")
.replace("}$", "")
.replace("\\$", "")
.replace("$", "")
.replace("{", "")
.replace("\\boxed", "")
)
def check_answer(item: Dict, model_answer: str):
question_type = item["question_type"]
correct_answer = str(item["answer"]) if item["answer"] is not None else ""
pred_answer = normalize_response(extract_result(model_answer))
if question_type == "numerical":
try:
model_value = float("".join(c for c in pred_answer if c.isdigit() or c in ".-"))
correct_value = float("".join(c for c in correct_answer if c.isdigit() or c in ".-"))
tolerance = float(item.get("tolerance", 0.0))
return abs(model_value - correct_value) <= tolerance, pred_answer
except (ValueError, TypeError):
return False, pred_answer
else:
model_answers = {c for c in pred_answer.upper() if c in "ABCDEFGHIJKLMN"}
correct_answers = {c for c in correct_answer.upper() if c in "ABCDEFGHIJKLMN"}
return model_answers == correct_answers, pred_answer
# ============ 单题推理 ============
def call_model_with_llava(
image: Image.Image | None,
question: str,
question_type: str,
options: str = "",
unit: str = "",
verified_caption: str = "",
related_sentences: str = "",
idx: int = -1,
) -> str:
# 用 caption / description 填充
if not verified_caption:
verified_caption = ""
if not related_sentences:
related_sentences = ""
if question_type == "numerical":
prompt = INSTRUCTIONS[question_type].format(
unit=unit, verified_caption=verified_caption, related_sentences=related_sentences
)
prompt += f"\nQuestion: {question}"
else:
prompt = INSTRUCTIONS[question_type].format(
verified_caption=verified_caption, related_sentences=related_sentences
)
prompt += f"\nQuestion: {question}"
if options:
prompt += f"\nOptions: {options}"
return llava_answer(prompt, image, idx=idx).strip()
# ============ 多进程处理单个样本 ============
def process_single_item(item: Dict):
try:
# 从 image_path 打开图片(因为 PIL Image 无法跨进程传递)
image = item.get("image", None)
img_path = item.get("image_path")
# 记录图像加载过程
log_inference(f"\n[IMAGE LOADING] idx={item.get('idx')}")
log_inference(f" - image_path field: {img_path}")
if image is None:
if img_path and os.path.exists(img_path):
image = Image.open(img_path).convert("RGB")
log_inference(f" - Status: LOADED from path")
else:
log_inference(f" - Status: NOT FOUND or path is None")
question = item.get("question", "")
q_type_raw = item.get("question_type", "single_choice")
# 映射问题类型到支持的格式
q_type_map = {
"single_choice": "single_choice",
"multiple_choice": "multiple_choice",
"multi_choice": "multiple_choice", # 兼容
"numerical": "numerical",
"other": "single_choice", # 默认当作单选
}
q_type = q_type_map.get(q_type_raw, "single_choice")
# options 是 list,需要拼成字符串
opts = item.get("options", [])
if isinstance(opts, list):
options_str = " ".join(opts)
else:
options_str = str(opts)
unit = str(item.get("unit") or "")
verified_caption = str(item.get("caption") or "")
related_sentences = str(item.get("description") or "")
sample_idx = int(item.get("id", item.get("idx", -1)))
model_answer = call_model_with_llava(
image=image,
question=question,
question_type=q_type,
options=options_str,
unit=unit,
verified_caption=verified_caption,
related_sentences=related_sentences,
idx=sample_idx,
)
is_correct, pred_answer = check_answer(item, model_answer)
del image
return {
"idx": int(item.get("id", item["idx"])),
"question_text": question,
"question_type": q_type,
"answer": item.get("answer"),
"options": options_str,
"unit": unit,
"verified_caption": verified_caption,
"related_sentences": related_sentences,
"tolerance": item.get("tolerance", 0.0) or 0.0,
"knowledge_domain": item.get("knowledge_domain", ""),
"model_answer": model_answer,
"pred_answer": pred_answer,
"correct_or_not": is_correct,
}
except Exception as e:
print(f"Error processing item {item.get('id', item.get('idx'))}: {e}")
return None
finally:
gc.collect()
# ============ 数据加载 & 增量评估 ============
import json
def load_dataset_streaming(dataset_name: str = None, split: str = "train") -> Iterator[Dict]:
"""
直接从本地 finmme_raw.jsonl + image_path 读取数据,不再访问 Hugging Face。
注意:只传递路径,不在这里打开图片(PIL Image 无法跨进程传递)
"""
jsonl_path = "/workspace/data/finmme_raw.jsonl" # 按你的真实路径修改
with open(jsonl_path, "r", encoding="utf-8") as f:
for idx, line in enumerate(f):
item = json.loads(line)
item["idx"] = idx
# 只保留路径,不打开图片
item["image"] = None # 稍后在推理时根据 image_path 打开
yield item
def calculate_finscore(df: pd.DataFrame):
if "knowledge_domain" not in df.columns or df["knowledge_domain"].isnull().all():
print("Warning: 'knowledge_domain' column not found or empty. Cannot calculate FinScore.")
return
domain_scores = df.groupby("knowledge_domain")["correct_or_not"].mean()
domain_normed_scores = domain_scores.mean()
multi_answer_df = df[
(df["question_type"] == "multiple_choice") & (df["answer"].astype(str).str.len() > 1)
]
hallucination_rate = 0.0
if not multi_answer_df.empty:
hallucination_rate = (~multi_answer_df["correct_or_not"]).mean()
finscore = domain_normed_scores * (1 - hallucination_rate)
print("-" * 20)
print("FinMME Benchmark Scores (LLaVA local):")
print(f"FinScore: {finscore:.4f}")
print(f"Domain-Normalized Score: {domain_normed_scores:.4f}")
print(f"Hallucination Rate (multi-answer subset): {hallucination_rate:.4f}")
print("-" * 20)
def main(
dataset_name: str = "luojunyu/FinMME",
split: str = "train",
sample_size: int | None = None,
num_processes: int = 4,
):
output_file = f"eval_hf_{MODEL_TAG}.csv" # 改用 CSV,不需要 openpyxl
# 1. 读取已有结果,实现断点续跑
try:
existing_df = pd.read_csv(output_file)
processed_indices = set(existing_df["idx"].tolist())
print(f"Loaded {len(existing_df)} existing results from {output_file}")
except FileNotFoundError:
existing_df = pd.DataFrame()
processed_indices = set()
# 2. 构造样本流
items_stream = (
item for item in load_dataset_streaming(dataset_name, split) if item["idx"] not in processed_indices
)
if sample_size:
from itertools import islice
items_stream = islice(items_stream, sample_size)
# 3. 推理(单进程直接迭代,因为 CUDA 模型无法跨进程共享)
new_results = []
FINMME_TOTAL_COUNT = 11099
total = sample_size if sample_size else FINMME_TOTAL_COUNT - len(processed_indices)
# 注意:LLaVA 模型在 GPU 上,不能用 multiprocessing.Pool
# 直接在主进程迭代
desc = "Processing (LLaVA local, single process)"
for item in tqdm(items_stream, total=total, desc=desc):
result = process_single_item(item)
if result:
new_results.append(result)
# 4. 合并 & 保存 & 统计
if not new_results and existing_df.empty:
print("No items processed; nothing to save.")
return
if new_results:
new_df = pd.DataFrame(new_results)
combined_df = (
pd.concat([existing_df, new_df], ignore_index=True)
.sort_values(by="idx")
.reset_index(drop=True)
)
else:
combined_df = existing_df
combined_df.to_csv(output_file, index=False)
print(f"\nResults saved to {output_file}")
accuracy = combined_df["correct_or_not"].mean()
print(f"Overall accuracy: {accuracy:.4%}")
calculate_finscore(combined_df)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", default="luojunyu/FinMME")
parser.add_argument("--split", default="train")
parser.add_argument("--sample_size", type=int, default=None)
parser.add_argument("--num_processes", type=int, default=4)
args = parser.parse_args()
main(args.dataset, args.split, args.sample_size, args.num_processes)
|