zeju-0727 commited on
Commit
4bb6284
·
verified ·
1 Parent(s): d2b2f27

Upload dyve_tts/eval/evaluate_pass_at_1_simple.py with huggingface_hub

Browse files
dyve_tts/eval/evaluate_pass_at_1_simple.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import asyncio
3
+ import aiofiles
4
+ from tqdm import tqdm
5
+ import os
6
+ import argparse
7
+ from openai import AsyncOpenAI
8
+ from math_verify import parse
9
+ from evaluate import load
10
+
11
+ math = load("competition_math")
12
+
13
+
14
+ async def generate_single_answer(client, question: str, model_name: str) -> str:
15
+ """Generate a single answer for a question using the language model."""
16
+
17
+ problem = question
18
+
19
+ prompt = f"""
20
+ The following is a math problem:
21
+
22
+ [Math Problem]
23
+
24
+ {problem}
25
+
26
+ Your task is to solve it step by step.
27
+ """
28
+
29
+ # Please put your final answer (i.e., the index) in \\boxed{{}}.
30
+ try:
31
+ response = await client.chat.completions.create(
32
+ model=model_name,
33
+ messages=[
34
+ {"role": "user", "content": prompt}
35
+ ],
36
+ max_tokens=8192,
37
+ temperature=0.6,
38
+ top_p=0.95,
39
+ n=1
40
+ )
41
+ return response.choices[0].message.content.strip()
42
+ except Exception as e:
43
+ print(f"Error in generate_single_answer: {str(e)}")
44
+ return None
45
+
46
+
47
+ async def evaluate_single_problem(
48
+ prob: dict,
49
+ client: AsyncOpenAI,
50
+ model_name: str,
51
+ sem: asyncio.Semaphore
52
+ ) -> dict:
53
+ async with sem:
54
+ try:
55
+ print("Evaluating problem: {}".format(prob["question"]))
56
+
57
+ # Generate single answer
58
+ answer = await generate_single_answer(client, prob["question"], model_name)
59
+ if answer is None:
60
+ return None
61
+
62
+ # Extract answer and check correctness
63
+ extracted_ans = parse(answer)
64
+ pass_at_1 = 1 if math.compute(references=[prob["expected_answer"]], predictions=[extracted_ans])["accuracy"] > 0.99 else 0
65
+
66
+ print("------------------------------------------------------------")
67
+ print("Question:", prob["question"])
68
+ print("Expected answer:", prob["expected_answer"])
69
+ print("Generated answer:", answer)
70
+ print("Pass@1:", pass_at_1)
71
+
72
+ result = {
73
+ "question": prob["question"],
74
+ "expected_answer": prob["expected_answer"],
75
+ "generated_answer": answer,
76
+ "pass@1": pass_at_1
77
+ }
78
+ return result
79
+ except Exception as e:
80
+ print(f"Error in evaluate_single_problem: {str(e)}")
81
+ return None
82
+
83
+
84
+ async def save_results_async(output_file: str, data: dict):
85
+ async with aiofiles.open(output_file, 'a') as f:
86
+ await f.write(json.dumps(data) + '\n')
87
+
88
+
89
+ async def main(debug: bool = False, resume: bool = False):
90
+ # Initialize the AsyncOpenAI client
91
+ client = AsyncOpenAI(
92
+ base_url="http://localhost:8014/v1",
93
+ api_key="token-abc123"
94
+ )
95
+
96
+ model_name = "DeepSeek-R1-Distill-Qwen-14B"
97
+
98
+ # Load problems from test500.jsonl
99
+ problems = []
100
+ with open('./test500.jsonl', 'r') as f:
101
+ for line in f:
102
+ problem = json.loads(line)
103
+ problems.append({
104
+ 'question': problem['problem'],
105
+ 'expected_answer': problem['answer']
106
+ })
107
+
108
+ # If debug flag is active, only evaluate the first 50 problems
109
+ if debug:
110
+ problems = problems[:50]
111
+ print("DEBUG MODE: processing only the first 50 problems.")
112
+
113
+ # If resume flag is active, skip already evaluated problems
114
+ output_file = "pass_at_1_simple_results.jsonl"
115
+ if resume:
116
+ if os.path.exists(output_file):
117
+ # Deduplicate the results file
118
+ dedup = {}
119
+ with open(output_file, 'r') as res_file:
120
+ for line in res_file:
121
+ if line.strip():
122
+ try:
123
+ rec = json.loads(line)
124
+ question = rec.get("question")
125
+ if question is not None:
126
+ dedup[question] = rec
127
+ except Exception as e:
128
+ continue
129
+
130
+ # Write deduplicated results back to the file
131
+ with open(output_file, 'w') as res_file:
132
+ for rec in dedup.values():
133
+ res_file.write(json.dumps(rec) + "\n")
134
+
135
+ evaluated_questions = set(dedup.keys())
136
+ original_count = len(problems)
137
+ problems = [p for p in problems if p["question"] not in evaluated_questions]
138
+ skipped = original_count - len(problems)
139
+ print(f"Resuming evaluation: Skipping {skipped} already evaluated problems.")
140
+ else:
141
+ print("No previous evaluation results found. Starting from scratch.")
142
+
143
+ # Create a semaphore to limit concurrent tasks
144
+ sem = asyncio.Semaphore(30) # Adjust the number based on your needs
145
+
146
+ # Create tasks for each problem
147
+ tasks = [
148
+ asyncio.create_task(evaluate_single_problem(prob, client, model_name, sem))
149
+ for prob in problems
150
+ ]
151
+
152
+ results = []
153
+ # Use as_completed to update progress with tqdm
154
+ for future in tqdm(asyncio.as_completed(tasks), total=len(tasks), desc='Processing problems'):
155
+ result = await future
156
+ if result is not None:
157
+ results.append(result)
158
+ # Save result immediately
159
+ await save_results_async(output_file, result)
160
+
161
+ if results:
162
+ total_pass_at_1 = sum(result["pass@1"] for result in results)
163
+ pass_at_1_rate = total_pass_at_1 / len(results) * 100
164
+ print(f"\nFinal Pass@1 Rate: {pass_at_1_rate:.2f}%")
165
+
166
+ print(f"Evaluation complete. Processed {len(results)} problems successfully.")
167
+ print(f"Results saved to {output_file}")
168
+
169
+
170
+ if __name__ == "__main__":
171
+ parser = argparse.ArgumentParser()
172
+ parser.add_argument("--debug", action="store_true", help="Run in debug mode (only evaluate the first 50 problems)")
173
+ parser.add_argument("--resume", action="store_true", help="Resume evaluation by skipping already evaluated problems")
174
+ args = parser.parse_args()
175
+ asyncio.run(main(debug=args.debug, resume=args.resume))