| |
| |
|
|
| 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() |
| |
| try: |
| if gt_text.startswith("[") and gt_text.endswith("]"): |
| gt_list = eval(gt_text) |
| else: |
| gt_list = [gt_text.strip()] |
| except: |
| gt_list = [gt_text.strip()] |
|
|
| |
| 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 |
|
|
| |
| 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." |
| ) |
| |
| 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_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 |
|
|
| |
| 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) |
|
|
| |
| 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}") |
| |
| continue |
|
|
| |
| 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) |
|
|
| |
| 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(): |
| |
| 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.") |
|
|
| |
| 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}") |
|
|
| |
| 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() |
|
|