NotoriousH2 commited on
Commit
48d87be
ยท
verified ยท
1 Parent(s): 10c8d20

Add eval.py

Browse files
Files changed (1) hide show
  1. eval.py +86 -0
eval.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """๊ณตํ†ต ํ‰๊ฐ€ ์Šคํฌ๋ฆฝํŠธ: vLLM ์„œ๋ฒ„์— ์—ฐ๊ฒฐํ•˜์—ฌ HRM8K ์ „์ฒด 841๋ฌธ์ œ ํ‰๊ฐ€ (temperature=0)"""
2
+ import os, json, re, sys, asyncio
3
+ from langchain_openai import ChatOpenAI
4
+ from langchain_core.prompts import ChatPromptTemplate
5
+ from langchain_core.output_parsers import StrOutputParser
6
+ from openai import OpenAI
7
+
8
+ MATH_SYSTEM_PROMPT = """์ฃผ์–ด์ง„ ์ˆ˜ํ•™ ๋ฌธ์ œ๋ฅผ ๋‹จ๊ณ„๋ณ„๋กœ ํ’€๊ณ  ๋‹ต๋ณ€์„ ์ž‘์„ฑํ•˜์„ธ์š”.
9
+ ๋ฐ˜๋“œ์‹œ ์ตœ์ข… ๋‹ต๋ณ€์„ \\boxed{์ •์ˆ˜} ํ˜•์‹์œผ๋กœ ๋งˆ์ง€๋ง‰ ์ค„์— ์ถœ๋ ฅํ•˜์„ธ์š”.
10
+ ์˜ˆ์‹œ: \\boxed{42}"""
11
+
12
+ def extract_boxed(text):
13
+ m = re.findall(r'\\boxed\{([^}]+)\}', text)
14
+ return m[-1].strip() if m else None
15
+
16
+ def normalize(a):
17
+ if a is None: return None
18
+ s = str(a).replace(",","").replace(" ","").strip()
19
+ try:
20
+ n = float(s)
21
+ return str(int(n)) if n == int(n) else str(n)
22
+ except: return s
23
+
24
+ def check(pred, gt):
25
+ p, g = normalize(pred), normalize(gt)
26
+ return p is not None and g is not None and p == g
27
+
28
+ async def evaluate(label="", save_path=None):
29
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="token-abc123")
30
+ model_name = client.models.list().data[0].id
31
+ print(f"๋ชจ๋ธ: {model_name}")
32
+
33
+ with open("data/HRM8k_eval.json") as f:
34
+ data = json.load(f)
35
+ print(f"ํ‰๊ฐ€: {len(data)}๊ฐœ (temperature=0, max_tokens=2048)")
36
+
37
+ llm = ChatOpenAI(base_url="http://localhost:8000/v1", api_key="token-abc123",
38
+ model=model_name, temperature=0, max_tokens=2048)
39
+ prompt = ChatPromptTemplate([("user", "{sp}\n\n{q}")]).partial(sp=MATH_SYSTEM_PROMPT)
40
+ chain = prompt | llm | StrOutputParser()
41
+ inputs = [{"q": item["question"]} for item in data]
42
+ results = await chain.abatch(inputs, config={"max_concurrency": 400})
43
+
44
+ by_src = {}
45
+ details = []
46
+ for item, res in zip(data, results):
47
+ s = item.get("source", "?")
48
+ if s not in by_src: by_src[s] = {"correct": 0, "total": 0, "no_boxed": 0}
49
+ by_src[s]["total"] += 1
50
+ pred = extract_boxed(res)
51
+ is_correct = False
52
+ if pred is None:
53
+ by_src[s]["no_boxed"] += 1
54
+ elif check(pred, item["answer"]):
55
+ by_src[s]["correct"] += 1
56
+ is_correct = True
57
+ details.append({
58
+ "question": item["question"][:80],
59
+ "source": s,
60
+ "gt": str(item["answer"])[-30:] if isinstance(item["answer"], str) else str(item["answer"]),
61
+ "pred": pred,
62
+ "correct": is_correct,
63
+ })
64
+
65
+ tc = sum(v["correct"] for v in by_src.values())
66
+ tt = sum(v["total"] for v in by_src.values())
67
+ print(f"\n=== {label} ๊ฒฐ๊ณผ (temperature=0) ===")
68
+ for s in sorted(by_src):
69
+ v = by_src[s]
70
+ print(f" [{s.upper()}] {v['correct']}/{v['total']} ({v['correct']/v['total']*100:.1f}%) | boxed๋ฏธ์ถœ๋ ฅ: {v['no_boxed']}")
71
+ print(f" [์ „์ฒด] {tc}/{tt} ({tc/tt*100:.1f}%)")
72
+
73
+ result_obj = {"label": label, "correct": tc, "total": tt, "accuracy": tc/tt*100, "by_source": by_src}
74
+
75
+ if save_path:
76
+ os.makedirs(os.path.dirname(save_path) or ".", exist_ok=True)
77
+ with open(save_path, "w") as f:
78
+ json.dump({"result": result_obj, "details": details}, f, ensure_ascii=False, indent=2)
79
+ print(f" ๊ฒฐ๊ณผ ์ €์žฅ: {save_path}")
80
+
81
+ return result_obj
82
+
83
+ if __name__ == "__main__":
84
+ label = sys.argv[1] if len(sys.argv) > 1 else "eval"
85
+ save_path = sys.argv[2] if len(sys.argv) > 2 else None
86
+ asyncio.run(evaluate(label, save_path))