interplane.Get Omega
Read in your language

aien-yardsticks

aien-dev/aien-yardsticks

Brought by drakestapleton

branch main Branches Tags History

aien-yardsticks / yardsticks / mojollama-eval-runners / eval / gsm8k.py

163 lines · 6626 bytes Raw Blame History
1"""GSM8K — Grade School Math benchmark.
2
38-shot chain-of-thought evaluation. Exact match accuracy on final answer.
4Uses openai/gsm8k dataset.
5"""
6
7import json
8import re
9import time
10from typing import Optional
11
12from .base import BaseBenchmark, LlamaCppEvaluator, extract_number_answer, normalize_answer
13from .dataset import get_dataset_stream
14
15
16# 8-shot CoT examples for GSM8K
17COT_EXAMPLES = [
18 {
19 "question": "Beth has 4 bags of marbles. Each bag has 24 marbles. She gives away 3 marbles. How many marbles does she have left?",
20 "answer": "Beth has 4 bags * 24 marbles = 96 marbles total. She gives away 3, so she has 96 - 3 = 93 marbles. #### 93"
21 },
22 {
23 "question": "Janet's ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins with four every day. She sells the rest at the farmers' market daily for $2 per fresh egg. How much in dollars does she make every day at the farmers' market?",
24 "answer": "She uses 3 + 4 = 7 eggs each day. She has 16 - 7 = 9 eggs left. She makes 9 * $2 = $18 each day. #### 18"
25 },
26 {
27 "question": "A robe takes 2 1/4 yards of material and a jacket takes 4 3/4 yards of material. How much more material does a jacket require than a robe?",
28 "answer": "4 3/4 - 2 1/4 = 2 1/2. The jacket requires 2 1/2 yards more. #### 2.5"
29 },
30 {
31 "question": "There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?",
32 "answer": "There are 15 trees initially and 21 after planting. So they planted 21 - 15 = 6 trees. #### 6"
33 },
34 {
35 "question": "If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?",
36 "answer": "There are originally 3 cars. 2 more arrive, so 3 + 2 = 5 cars. #### 5"
37 },
38 {
39 "question": "Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?",
40 "answer": "Originally, Leah had 32 and her sister had 42, so 32 + 42 = 74. They ate 35, so 74 - 35 = 39 pieces left. #### 39"
41 },
42 {
43 "question": "Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?",
44 "answer": "Shawn started with 5 toys. He got 2 from mom and 2 from dad, so 5 + 2 + 2 = 9 toys. #### 9"
45 },
46 {
47 "question": "There were nine computers in the server room. Five more computers were installed each day, from Monday to Thursday. How many computers are now in the server room?",
48 "answer": "There were originally 9 computers. From Monday to Thursday is 4 days. Each day 5 computers are installed, so 4 * 5 = 20 computers. Total: 9 + 20 = 29 computers. #### 29"
49 }
50]
51
52
53def _build_gsm8k_prompt(question, use_cot=True):
54 """Build a GSM8K prompt with 8-shot CoT examples."""
55 prompt_lines = []
56
57 for ex in COT_EXAMPLES:
58 prompt_lines.append(f"Question: {ex['question']}")
59 prompt_lines.append(f"Answer: {ex['answer']}")
60 prompt_lines.append("")
61
62 prompt_lines.append(f"Question: {question}")
63 prompt_lines.append("Answer:")
64
65 return "\n".join(prompt_lines)
66
67
68def _extract_gsm8k_answer(text: str) -> Optional[str]:
69 """Extract the final numeric answer from GSM8K output."""
70 # Look for #### N pattern
71 m = re.search(r'####\s*(-?\d+(?:[.,]\d+)?)', text)
72 if m:
73 return m.group(1).replace(",", "")
74
75 # Try to get the last number mentioned
76 numbers = re.findall(r'-?\d+(?:[.,]\d+)?', text)
77 if numbers:
78 return numbers[-1].replace(",", "")
79
80 return None
81
82
83class GSM8KBenchmark(BaseBenchmark):
84 """GSM8K benchmark — 8-shot chain-of-thought math word problems."""
85
86 @property
87 def name(self) -> str:
88 return "GSM8K"
89
90 def run(self, backend_url: str, model_name: str,
91 max_samples: int = 0, use_cot: bool = True,
92 **kwargs) -> dict:
93 evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=512)
94 t0 = time.time()
95
96 records = get_dataset_stream("gsm8k")
97 if not records:
98 return {
99 "name": "GSM8K",
100 "accuracy": 0, "correct": 0, "total": 0,
101 "per_category": {},
102 "metrics": {"elapsed": time.time() - t0, "api_calls": 0, "api_errors": 0},
103 "samples": 0,
104 "error": "No dataset found. Run `mojollama-studio evaluate download` first."
105 }
106
107 if max_samples > 0:
108 records = records[:max_samples]
109
110 correct = 0
111 total = 0
112 errors = 0
113
114 for i, record in enumerate(records):
115 question = record.get("question", "")
116 answer = record.get("answer", "")
117
118 # Extract ground truth answer (after ####)
119 gt = _extract_gsm8k_answer(answer)
120 if gt is None:
121 continue
122
123 prompt = _build_gsm8k_prompt(question, use_cot)
124
125 try:
126 generated = evaluator.complete(prompt, max_tokens=256,
127 stop=["Question:"])
128 predicted = _extract_gsm8k_answer(generated)
129 if predicted and normalize_answer(predicted) == normalize_answer(gt):
130 correct += 1
131 elif predicted:
132 # Try numeric comparison
133 try:
134 if abs(float(predicted) - float(gt)) < 0.01:
135 correct += 1
136 except (ValueError, TypeError):
137 pass
138 except Exception as e:
139 errors += 1
140
141 total += 1
142
143 if (i + 1) % 20 == 0 or (i + 1) == len(records):
144 pct = (correct / total * 100) if total > 0 else 0
145 print(f" GSM8K: {pct:.1f}% ({correct}/{total}) — {i+1}/{len(records)}")
146
147 elapsed = time.time() - t0
148 stats = evaluator.get_stats()
149
150 return {
151 "name": "GSM8K",
152 "accuracy": correct / total if total > 0 else 0,
153 "correct": correct,
154 "total": total,
155 "per_category": {"math": {"correct": correct, "total": total, "accuracy": correct / total if total > 0 else 0}},
156 "metrics": {
157 "elapsed": elapsed,
158 "api_calls": stats["api_calls"],
159 "api_errors": stats["api_errors"],
160 "total_tokens": stats["total_tokens"],
161 },
162 "samples": total
163 }