File size: 4,966 Bytes
d4a7e84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
from math_verify import parse, verify
from typing import Dict, Any
from collections import Counter
import argparse

def simple_verify(gold_answer: str, output_text: str) -> Dict[str, Any]:
    """
    使用math_verify进行简单验证
    与原有infer.py保持一致
    """
    try:
        # gold_answer = "$" + gold_answer + "$"
        gold = parse(gold_answer)
        answer = parse(output_text)
        verify_result = verify(gold, answer)
        extracted_answer = str(answer) if answer is not None else None
    except Exception as e:
        verify_result = False
        extracted_answer = None
        print(f"解析失败: {e}")
    return {
        'extracted_predicted': extracted_answer,
        'is_correct': verify_result
    }

def majority_verify(input_path, output_path,all_samples=False,clip_sample_num=4):
    total_len = 0
    majority_correct_len = 0
    correct_count_dict = {}
    correct_indices = []
    with open(input_path, 'r', encoding='utf-8') as f:
        for idx, line in enumerate(f):
            data = json.loads(line)
            solution = data['solution']
            if all_samples:
                outputs_list = data['outputs']
            else:
                if len(data['outputs']) < clip_sample_num:
                    outputs_list = data['outputs']
                else:
                    outputs_list = data['outputs'][:clip_sample_num]

            answer_counts = {}
            answer_verify_counts = {}
            verify_infos = []
            for output in outputs_list:
                verify_info = simple_verify(solution, output)
                extracted_answer = verify_info['extracted_predicted']
                normalized_answer = str(extracted_answer).strip() if extracted_answer is not None else None
                verify_infos.append((normalized_answer, verify_info['is_correct']))
                if normalized_answer is None:
                    continue
                answer_counts[normalized_answer] = answer_counts.get(normalized_answer, 0) + 1
                if normalized_answer not in answer_verify_counts:
                    answer_verify_counts[normalized_answer] = {'correct': 0, 'total': 0}
                answer_verify_counts[normalized_answer]['total'] += 1
                if verify_info['is_correct']:
                    answer_verify_counts[normalized_answer]['correct'] += 1

            if not answer_counts:
                correct_count_dict[idx] = 0
                total_len += 1
                continue

            # 打印每个问题的答案出现次数
            print(f"问题{idx} 答案出现次数:")
            for ans, cnt in answer_counts.items():
                print(f"({ans}):{cnt}次")

            # 找到出现次数最多的答案
            final_answer = max(answer_counts.items(), key=lambda x: x[1])[0]
            verify_info_majority = answer_verify_counts.get(final_answer, {'correct': 0, 'total': 0})
            verify_result = verify_info_majority['correct'] > 0
            if verify_result:
                majority_correct_len += 1
                correct_indices.append(idx)

            # 统计所有 sample 里正确的个数
            correct_count = sum(1 for _, is_correct in verify_infos if is_correct)
            correct_count_dict[idx] = correct_count
            total_len += 1

    acc = majority_correct_len / total_len if total_len > 0 else 0.0
    print(f"total_len: {total_len}, majority_correct_len: {majority_correct_len}")
    print(f"majority accuracy: {acc}")
    result = {
        'acc': acc,
        'correct_count_dict': correct_count_dict,
        'correct_indices': correct_indices
    }
    with open(output_path, 'w', encoding='utf-8') as fout:
        json.dump(result, fout, ensure_ascii=False, indent=2)
    dist = Counter(correct_count_dict.values())
    print("每个问题 sample 正确数量的分布:")
    for k in sorted(dist.keys(), reverse=True):
        print(f"{k} 个 sample 全对的问题数: {dist[k]}")

# input_path = "/home/tianqiu/tts_schedule/batch_infer/results/mathhard/Qwen_Qwen2.5-7B-Instruct/Sequence_new_prompt/batch_data/batch_1/parallel_merged_output.jsonl"
# output_path = "/home/tianqiu/tts_schedule/batch_infer/results/mathhard/Qwen_Qwen2.5-7B-Instruct/Sequence_new_prompt/batch_data/batch_1/acc.jsonl"
# majority_verify(input_path, output_path)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--input_path", type=str, required=True)
    parser.add_argument("--output_path", type=str, required=True)
    parser.add_argument("--all_samples", action="store_true")
    parser.add_argument("--clip_sample_num", type=int, required=True)
    args = parser.parse_args()
    input_path = args.input_path
    output_path = args.output_path
    all_samples = args.all_samples
    clip_sample_num = args.clip_sample_num
    majority_verify(input_path, output_path, False, clip_sample_num)