oExz commited on
Commit
54c1b43
·
verified ·
1 Parent(s): 057ac42

Upload eval_gsm8k_custom.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. eval_gsm8k_custom.py +63 -0
eval_gsm8k_custom.py CHANGED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "datasets",
5
+ # "transformers>=4.40.0",
6
+ # "torch>=2.0.0",
7
+ # "huggingface-hub",
8
+ # "accelerate",
9
+ # "bitsandbytes",
10
+ # ]
11
+ # ///
12
+
13
+ import os
14
+ import re
15
+ from datasets import load_dataset
16
+
17
+ os.environ.setdefault("HF_HUB_TOKEN", os.getenv("HF_TOKEN", ""))
18
+ MODEL = os.getenv("MODEL", "Qwen/Qwen3.5-4B")
19
+ LIMIT = int(os.getenv("LIMIT", "250"))
20
+
21
+ print(f"Loading GSM8K dataset (limit={LIMIT})...")
22
+ ds = load_dataset("openai/gsm8k", "main", split="test").select(range(min(LIMIT, 1319)))
23
+
24
+ print(f"Loading model {MODEL}...")
25
+ from transformers import AutoTokenizer, AutoModelForCausalLM
26
+ import torch
27
+
28
+ tok = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=True)
29
+ m = AutoModelForCausalLM.from_pretrained(
30
+ MODEL, trust_remote_code=True, device_map="auto", torch_dtype=torch.bfloat16
31
+ )
32
+
33
+ sys_msg = "You are a helpful assistant that solves math problems step by step."
34
+ correct = 0
35
+ total = len(ds)
36
+
37
+ for i, ex in enumerate(ds):
38
+ msgs = [
39
+ {"role": "system", "content": sys_msg},
40
+ {"role": "user", "content": f"Solve this math problem step by step. End your answer with 'ANSWER: <number>'\n\n{ex['question']}"},
41
+ ]
42
+ inp = tok.apply_chat_template(msgs, tokenize=True, return_tensors="pt", add_generation_prompt=True)
43
+ inp = {k: v.to(m.device) for k, v in inp.items()}
44
+ out = m.generate(**inp, max_new_tokens=512, do_sample=False)
45
+ gen = tok.decode(out[0][inp["input_ids"].shape[1]:], skip_special_tokens=True)
46
+
47
+ gt_match = re.search(r"####\s*(-?\d[\d,]*\.?\d*)", ex["answer"])
48
+ gt = gt_match.group(1).replace(",", "") if gt_match else ex["answer"].strip().split()[-1]
49
+
50
+ pred_match = re.search(r"ANSWER:\s*(-?\d[\d,]*\.?\d*)", gen)
51
+ if pred_match:
52
+ pred = pred_match.group(1).replace(",", "")
53
+ else:
54
+ nums = re.findall(r"-?\d[\d,]*\.?\d*", gen)
55
+ pred = nums[-1].replace(",", "") if nums else ""
56
+
57
+ if pred == gt:
58
+ correct += 1
59
+ if i < 5:
60
+ print(f"Q{i+1}: GT={gt} Pred={pred} OK={pred==gt}")
61
+
62
+ accuracy = correct / total * 100
63
+ print(f"\nGSM8K: {correct}/{total} = {accuracy:.2f}%")