File size: 7,136 Bytes
3b2d368 | 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 | import os
import re
import torch
import ast
import json
import shutil
import csv
import multiprocessing
import queue
from pathlib import Path
from tqdm import tqdm
from typing import List, Dict, Optional, Union
# =============================================================================
# 独立执行器:必须在类定义外,以支持多进程序列化
# =============================================================================
def _code_runner_worker(q, code_str):
"""在完全隔离的进程中运行代码"""
try:
# 严格限制执行环境,只允许基础数学运算
safe_globals = {
"__builtins__": {
"abs": abs, "round": round, "min": min, "max": max, "sum": sum,
"int": int, "float": float, "str": str, "len": len, "range": range,
"list": list, "dict": dict, "set": set, "tuple": tuple,
"True": True, "False": False, "None": None,
"math": __import__("math")
}
}
safe_locals = {}
# 拼接调用函数
full_code = f"{code_str}\n\nresult = simple_math_problem()"
# 执行
exec(full_code, safe_globals, safe_locals)
# 将结果回传给主进程
res = safe_locals.get('result')
q.put(res)
except Exception:
q.put(None)
# =============================================================================
# Generator 类定义
# =============================================================================
class Generator:
def __init__(self, config, model, tokenizer, device="cuda", output_dir=None):
self.config = config.generation
self.model = model.eval().to(device)
self.tokenizer = tokenizer
self.device = device
self.output_dir = output_dir or Path('output')
# 获取数据集名称
self.dataset_name = getattr(config, 'dataset', "chat")
if not isinstance(self.dataset_name, str):
self.dataset_name = getattr(self.dataset_name, 'dataset_name', "chat")
self.is_tinygsm = "tinygsm" in self.dataset_name.lower()
print(f"[Generator] Mode: {'TinyGSM (Evaluation)' if self.is_tinygsm else 'Chat'}")
def generate(self, prompt: Optional[str] = None):
if self.is_tinygsm:
return self._generate_tinygsm()
return self._generate_chat(prompt)
def _execute_math_code(self, code: str, timeout: int = 20) -> Optional[float]:
"""核心:多进程执行器,防止死循环卡死"""
if not code or 'def simple_math_problem' not in code:
return None
# 长度过滤:防止解析乱码耗时
if len(code) > 30000:
return None
# 使用 spawn 上下文,确保与 GPU 兼容
ctx = multiprocessing.get_context('spawn')
q = ctx.Queue()
p = ctx.Process(target=_code_runner_worker, args=(q, code))
p.start()
p.join(timeout) # 强制等待 timeout 秒
if p.is_alive():
p.terminate() # 强杀卡住的进程
p.join()
return None
try:
result = q.get_nowait()
return float(result) if result is not None else None
except (queue.Empty, ValueError, TypeError):
return None
def _generate_solutions(self, questions, ground_truth):
"""生成并实时验证准确率"""
results = {'questions': [], 'generated_solutions': [], 'executed_answers': [], 'full_outputs': []}
correct, total = 0, 0
pbar = tqdm(zip(questions, ground_truth), total=len(questions), desc="GSM8K Eval")
for idx, (question, truth_val) in enumerate(pbar):
prompt = f"<|bos|>Question: {question}\n\nSolution:\ndef simple_math_problem() -> int:\n # {question}\n "
# 生成
input_ids = torch.tensor([self.tokenizer.encode(prompt)], dtype=torch.long).to(self.device)
with torch.no_grad():
outputs = self.model.generate(
input_ids,
max_generation_length=512,
tokenizer=self.tokenizer,
temperature=0.7, # 数学建议低温
top_p=0.95
)
full_text = self.tokenizer.decode(outputs[0].tolist())
# 提取与执行
code = self._extract_function_code(full_text)
answer = self._execute_math_code(code, timeout=60)
# 实时对比
is_correct = self._compare_answers(answer, truth_val)
if is_correct: correct += 1
total += 1
# 更新进度条
pbar.set_postfix({"Acc": f"{correct/total:.2%}"})
# 收集结果
results['questions'].append(question)
results['executed_answers'].append(answer)
results['full_outputs'].append({'question': question, 'code': code, 'answer': answer, 'truth': truth_val})
# 定期清理显存
if idx % 20 == 0: torch.cuda.empty_cache()
return results, {"correct": correct, "total": total, "accuracy": correct/total}
def _extract_function_code(self, text):
"""正则匹配提取完整的 Python 函数"""
match = re.search(r'def simple_math_problem\(\).*?(\n\s+return.*?(?=\n\S|$))', text, re.DOTALL)
if match: return match.group(0)
# 备选逻辑:寻找 def 之后所有带缩进的行
lines = text.split('\n')
code_lines = []
in_func = False
for line in lines:
if 'def simple_math_problem' in line:
in_func = True
code_lines.append(line)
continue
if in_func:
if line.startswith(' ') or line.startswith('\t') or not line.strip():
code_lines.append(line)
else: break
return '\n'.join(code_lines) if code_lines else None
def _compare_answers(self, pred, truth) -> bool:
if pred is None: return False
try:
return abs(float(pred) - float(truth)) < 1e-5
except: return False
def _generate_tinygsm(self):
"""TinyGSM 数据集主逻辑"""
from datasets import load_dataset
ds = load_dataset("openai/gsm8k", "main", split="test")
questions = [s['question'] for s in ds]
# 提取标准答案(#### 后的数字)
ground_truth = [re.search(r'####\s*([+-]?[\d,]+\.?\d*)', s['answer']).group(1).replace(',', '') for s in ds]
results, summary = self._generate_solutions(questions, ground_truth)
# 保存
self.output_dir.mkdir(parents=True, exist_ok=True)
with open(self.output_dir / "gsm8k_metrics.txt", 'w') as f:
f.write(json.dumps(summary, indent=4))
print(f"\n✅ Evaluation Finished! Accuracy: {summary['accuracy']:.2%}")
return results |