awdwadali / test.py
eve1f's picture
Add files using upload-large-folder tool
afcd0ff verified
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import glob
import string
import torch
import librosa
import soundfile as sf
import jiwer
from tqdm.auto import tqdm
from collections import defaultdict
from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor
from datasets import load_dataset
from qwen_omni_utils import process_mm_info
import datasets
import csv
# ---- 文本预处理 & 评分 ----
def preprocess_text(text: str) -> str:
return text.lower().translate(str.maketrans("", "", string.punctuation))
def validate_prediction(pred: str, gt_text: str, bm: str) -> float:
bm = bm.lower()
if bm in ["llama-questions", "voicebench"]:
return 1.0 if preprocess_text(gt_text) in preprocess_text(pred) else 0.0
if bm in ["mmar", "mmau"]:
return 1.0 if gt_text.strip() in pred.strip() else 0.0
elif bm in ["speech-triavia-qa", "speech-web-questions"]:
# 把预测结果左右空白去掉
pred_stripped = pred.strip()
# 尝试把 gt_text 解析成列表
try:
if gt_text.startswith("[") and gt_text.endswith("]"):
gt_list = eval(gt_text) # 或者用 json.loads 更安全
else:
gt_list = [gt_text.strip()]
except:
gt_list = [gt_text.strip()]
# 改成:只要列表中任意一个 gt 子串出现在预测里,就算正确
score = 1.0 if any(gt.strip() in pred_stripped for gt in gt_list) else 0.0
if bm == "tedlium":
wer = jiwer.wer(gt_text, pred)
return max(0.0, 1.0 - wer)
return 0.0
# ---- 对单个 checkpoint 评估,返回 (overall, {bm_modality: acc}) ----
def evaluate_checkpoint(ckpt_path: str, eval_dataset) -> tuple[float, dict]:
print(f"\n>>> Loading model from {ckpt_path}")
model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
ckpt_path, torch_dtype="auto", device_map="cuda:1"
)
processor = Qwen2_5OmniProcessor.from_pretrained(ckpt_path)
# 音频重采样缓存目录
resampled_dir = "/home/chenyifu/new_rl/dissrc/evaluategemini"
os.makedirs(resampled_dir, exist_ok=True)
# 准备错误记录文件
err_path = os.path.join(
resampled_dir,
f"errors_{os.path.basename(ckpt_path)}.csv"
)
err_f = open(err_path, "w", newline="", encoding="utf-8")
err_writer = csv.writer(err_f)
err_writer.writerow([
"sample_id", "benchmark_type", "modality", "ground_truth", "prediction"
])
scores_by_bm_modality = defaultdict(list)
for sample in tqdm(eval_dataset, desc=" Samples", leave=False):
bm = sample["benchmark_type"].lower()
if bm in ["uro-bench", "wavbench","speech-triavia-qa", "speech-web-questions"]:
continue
gt_text = sample["answer"]
sample_id = sample["id"]
system_prompt = (
"You are Qwen, a virtual human developed by the Qwen Team, "
"Alibaba Group, capable of perceiving auditory and visual inputs, "
"as well as generating text and speech."
)
# 选 system_content
if bm == "tedlium":
system_content = (
"You are an expert in automatic speech recognition, "
"and you are asked to recognize and output the content of this speech. "
"Note! Just output the content corresponding to the speech, and don't have any other words"
)
else:
system_content = (
"Please answer the questions with clear and concise answers, "
"do not output any other explanation"
)
# —— Audio 模态 ——
audio_path = sample["audio"].replace(
"/root/autodl-tmp/", "/home/chenyifu/new_rl/"
)
try:
if os.path.exists(audio_path):
info = sf.info(audio_path)
if info.samplerate != 16000:
data, sr = librosa.load(audio_path, sr=None)
data_resampled = librosa.resample(
data, orig_sr=sr, target_sr=16000
)
audio_path_for_model = os.path.join(
resampled_dir, f"{sample_id}_resampled.wav"
)
sf.write(audio_path_for_model, data_resampled, 16000)
else:
audio_path_for_model = audio_path
# 如果有 transcription,一并加到 conv_audio
if sample["transcription"]:
conv_audio = [
{"role":"system", "content":[{"type":"text","text":system_prompt}]},
{"role":"user", "content":[
{"type":"audio","audio":audio_path_for_model},
{"type":"text", "text":sample["transcription"]+system_content}
]}
]
else:
conv_audio = [
{"role":"system", "content":[{"type":"text","text":system_prompt}]},
{"role":"user", "content":[{"type":"text","text":system_content},{"type":"audio","audio":audio_path_for_model}]}
]
text_prompt = processor.apply_chat_template(
conv_audio, add_generation_prompt=True, tokenize=False
)
audios, _, _ = process_mm_info(
conv_audio, use_audio_in_video=False
)
inputs = processor(
text=text_prompt, audio=audios, return_tensors="pt"
).to(model.device)
text_ids = model.generate(
**inputs, return_audio=False,
do_sample=False, use_audio_in_video=False
)
pred = processor.batch_decode(
text_ids, skip_special_tokens=True,
clean_up_tokenization_spaces=False
)[0].split("assistant\n")[-1].strip()
score = validate_prediction(pred, gt_text, bm)
scores_by_bm_modality[(bm, "audio")].append(score)
# **新增**:预测错误则写入 CSV
if score < 1.0:
err_writer.writerow([
sample_id, bm, "audio", gt_text, pred
])
except Exception as e:
print(f"{e} in index {sample_id}")
# 可以视需要,也把异常记录到 err_writer
continue
# —— Text 模态 ——
question = sample.get("question", "")
transcription = sample.get("transcription", "")
if question:
try:
conv_text = [
{"role":"system", "content":[{"type":"text","text":system_prompt}]},
{"role":"user", "content":[{"type":"text","text":question+system_content}]}
]
text_prompt = processor.apply_chat_template(
conv_text, add_generation_prompt=True, tokenize=False
)
inputs = processor(
text=text_prompt, return_tensors="pt"
).to(model.device)
text_ids = model.generate(
**inputs, return_audio=False,
do_sample=False, use_audio_in_video=False
)
pred = processor.batch_decode(
text_ids, skip_special_tokens=True,
clean_up_tokenization_spaces=False
)[0].split("assistant\n")[-1].strip()
score = validate_prediction(pred, gt_text, bm)
scores_by_bm_modality[(bm, "text")].append(score)
# **新增**:预测错误则写入 CSV
if score < 1.0:
err_writer.writerow([
sample_id, bm, "text", gt_text, pred
])
except Exception as e:
print(f"{e} in index {sample_id}")
continue
# 关闭错误记录文件,释放模型和显存
err_f.close()
del model
torch.cuda.empty_cache()
# 计算总体 & 各分组准确率
all_scores = [
s for scores in scores_by_bm_modality.values() for s in scores
]
overall = sum(all_scores) / len(all_scores) if all_scores else 0.0
accuracies = {
f"{bm}_{modality}": sum(scores) / len(scores)
for (bm, modality), scores in scores_by_bm_modality.items()
}
print(f" → 保存错误示例到 {err_path}")
return overall, accuracies
# ---- 主函数 ----
def main():
# 1) 加载数据集
dataset_path = "/home/chenyifu/new_rl/dataset/validation"
if not os.path.exists(dataset_path):
raise FileNotFoundError(f"{dataset_path} not found")
eval_dataset = datasets.load_from_disk(dataset_path)
print(f"Loaded dataset with {len(eval_dataset)} samples.")
# 2) 收集所有 checkpoint 并排序
ckpt_glob = "/home/chenyifu/new_rl/dissrc/qwenomnithinker_rl/exp/gemini_model_s0.8a0.2/checkpoint-*"
ckpts = sorted(glob.glob(ckpt_glob), key=lambda x: int(x.rsplit("-",1)[1]))
print(f"Found {len(ckpts)} checkpoints under {ckpt_glob}")
# # 3) 逐 checkpoint 评估并打印结果
for ckpt in tqdm(ckpts, desc="Checkpoints"):
overall, accs = evaluate_checkpoint(ckpt, eval_dataset)
name = os.path.basename(ckpt)
print(f"\n=== Results for {name} ===")
print(f"总体平均准确率: {overall:.4f}")
print("-" * 50)
for key in sorted(accs):
print(f"{key}_accuracy: {accs[key]:.4f}")
if __name__ == "__main__":
main()