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