Maxenith commited on
Commit
ae0a690
ยท
verified ยท
1 Parent(s): 5630640

Add evaluation script

Browse files
Files changed (1) hide show
  1. gsm8k_full_final.py +163 -0
gsm8k_full_final.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc, re, time, json, math, torch
2
+ from datasets import load_dataset
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+
5
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ุงู„ุฅุนุฏุงุฏุงุช (ู†ูุณู‡ุง ู„ู„ู†ู…ูˆุฐุฌูŠู†) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
6
+ ORIGINAL_ID = "Qwen/Qwen3.5-9B"
7
+ MY_ID = "Maxenith/MAX-9B"
8
+ THINKING = True
9
+ SYSTEM = "You are a helpful assistant."
10
+ N = None # None = ุงู„ุงุฎุชุจุงุฑ ูƒุงู…ู„ุงู‹ (1319 ุณุคุงู„ุงู‹)
11
+
12
+ BATCH = 64 # ุงู„ู…ุฑุญู„ุฉ 1
13
+ MAX_NEW = 2048
14
+ RETRY_BATCH = 32 # ุงู„ู…ุฑุญู„ุฉ 2: ุฅุนุงุฏุฉ ุงู„ุฃุณุฆู„ุฉ ุงู„ู…ู‚ุทูˆุนุฉ ูู‚ุท
15
+ MAX_NEW_2 = 8192
16
+
17
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ุงู„ุจูŠุงู†ุงุช โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
18
+ ds = load_dataset("openai/gsm8k", "main", split="test")
19
+ if N:
20
+ ds = ds.shuffle(seed=42).select(range(N))
21
+ n = len(ds)
22
+ print(f"Questions: {n}")
23
+
24
+ NUM = r"-?\d[\d,]*\.?\d*"
25
+
26
+ def to_float(s):
27
+ try:
28
+ return float(s.replace(",", "").rstrip("."))
29
+ except Exception:
30
+ return None
31
+
32
+ def get_truth(answer_text):
33
+ return to_float(answer_text.split("####")[-1].strip())
34
+
35
+ def extract_pred(text):
36
+ """ูŠุนูŠุฏ (ุงู„ุฑู‚ู…, ู‡ู„ ุงูƒุชู…ู„ ุงู„ุชููƒูŠุฑ)."""
37
+ if THINKING:
38
+ if "</think>" not in text:
39
+ return None, False
40
+ text = text.split("</think>")[-1]
41
+ m = re.findall(r"Answer:\s*\$?\s*(" + NUM + ")", text)
42
+ if m:
43
+ return to_float(m[-1]), True
44
+ nums = re.findall(NUM, text)
45
+ return (to_float(nums[-1]) if nums else None), True
46
+
47
+ def build_prompt(tok, q):
48
+ msgs = [
49
+ {"role": "system", "content": SYSTEM},
50
+ {"role": "user", "content": q + "\nSolve this step by step and put the final answer after the word 'Answer:'."},
51
+ ]
52
+ return tok.apply_chat_template(
53
+ msgs, tokenize=False, add_generation_prompt=True, enable_thinking=THINKING
54
+ )
55
+
56
+ dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
57
+
58
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ุงู„ุชูˆู„ูŠุฏ ุจุฏูุนุงุช โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
59
+ def generate_many(model, tok, prompts, idx_list, max_new, batch, label):
60
+ """ูŠุนูŠุฏ {index: (text, n_generated_tokens)}"""
61
+ order = sorted(idx_list, key=lambda i: len(prompts[i]))
62
+ res, t0 = {}, time.time()
63
+ for b in range(0, len(order), batch):
64
+ idx = order[b:b + batch]
65
+ enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True).to(model.device)
66
+ with torch.no_grad():
67
+ out = model.generate(**enc, max_new_tokens=max_new, do_sample=False,
68
+ pad_token_id=tok.pad_token_id)
69
+ gen = out[:, enc["input_ids"].shape[1]:]
70
+ ntoks = (gen != tok.pad_token_id).sum(dim=1).tolist()
71
+ texts = tok.batch_decode(gen, skip_special_tokens=True)
72
+ for i, t, k in zip(idx, texts, ntoks):
73
+ res[i] = (t, k)
74
+ print(f" [{label}] {len(res)}/{len(order)} | {time.time() - t0:.0f}s")
75
+ return res
76
+
77
+ def score(i, text, ntok, truths):
78
+ pred, finished = extract_pred(text)
79
+ ok = pred is not None and truths[i] is not None and abs(pred - truths[i]) < 1e-4
80
+ return {"i": i, "truth": truths[i], "pred": pred, "ok": ok,
81
+ "finished": finished, "tokens": ntok, "output": text}
82
+
83
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ุชู‚ูŠูŠู… ู†ู…ูˆุฐุฌ ูˆุงุญุฏ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
84
+ def run_eval(name, model_id):
85
+ print("\n" + "=" * 50)
86
+ print(f" {name}: {model_id}")
87
+ print("=" * 50)
88
+
89
+ tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
90
+ tok.padding_side = "left"
91
+ if tok.pad_token is None:
92
+ tok.pad_token = tok.eos_token
93
+ model = AutoModelForCausalLM.from_pretrained(
94
+ model_id, torch_dtype=dtype, device_map={"": 0}, trust_remote_code=True
95
+ ).eval()
96
+
97
+ prompts = [build_prompt(tok, x["question"]) for x in ds]
98
+ truths = [get_truth(x["answer"]) for x in ds]
99
+
100
+ # ุงู„ู…ุฑุญู„ุฉ 1
101
+ res = generate_many(model, tok, prompts, list(range(n)), MAX_NEW, BATCH, "stage1")
102
+ records = [score(i, *res[i], truths) for i in range(n)]
103
+ pending = [i for i in range(n) if not records[i]["finished"]]
104
+ print(f" Stage 1: accuracy {sum(r['ok'] for r in records) / n * 100:.1f}% | "
105
+ f"truncated: {len(pending)}")
106
+
107
+ # ุงู„ู…ุฑุญู„ุฉ 2: ุฅุนุงุฏุฉ ุงู„ู…ู‚ุทูˆุนุฉ ูู‚ุท ุจุญุฏ ุฃูƒุจุฑ (ู†ูุณ ุงู„ู†ุชูŠุฌุฉ ุงู„ุชูŠ ูƒุงู†ุช ุณุชุธู‡ุฑ ู„ูˆ ูƒุงู† ุงู„ุญุฏ ูƒุจูŠุฑุงู‹ ู…ู† ุงู„ุจุฏุงูŠุฉ)
108
+ if pending:
109
+ print(f" Stage 2: re-running {len(pending)} truncated questions with max_new={MAX_NEW_2}")
110
+ res2 = generate_many(model, tok, prompts, pending, MAX_NEW_2, RETRY_BATCH, "stage2")
111
+ for i in pending:
112
+ records[i] = score(i, *res2[i], truths)
113
+
114
+ with open(f"results_{name}.json", "w") as f:
115
+ json.dump({"model": model_id, "records": records}, f, ensure_ascii=False)
116
+
117
+ del model, tok
118
+ gc.collect(); torch.cuda.empty_cache()
119
+ return records
120
+
121
+ # โ”€๏ฟฝ๏ฟฝโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ุงู„ุชุดุบูŠู„ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
122
+ all_rec = {}
123
+ all_rec["MAX-9B"] = run_eval("MAX-9B", MY_ID)
124
+ all_rec["Original"] = run_eval("Original", ORIGINAL_ID)
125
+
126
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ุงู„ู†ุชุงุฆุฌ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
127
+ def margin(acc, m):
128
+ p = acc / 100
129
+ return 1.96 * math.sqrt(p * (1 - p) / m) * 100
130
+
131
+ print("\n" + "=" * 56)
132
+ print(f" FINAL SCOREBOARD (GSM8K, {n} questions, thinking={THINKING})")
133
+ print("=" * 56)
134
+ accs = {}
135
+ for k, rec in all_rec.items():
136
+ acc = sum(r["ok"] for r in rec) / n * 100
137
+ accs[k] = acc
138
+ trunc = sum(not r["finished"] for r in rec)
139
+ avg_tok = sum(r["tokens"] for r in rec) / n
140
+ fin = [r for r in rec if r["finished"]]
141
+ acc_fin = sum(r["ok"] for r in fin) / max(len(fin), 1) * 100
142
+ print(f" {k:9s}: {acc:.1f}% (ยฑ{margin(acc, n):.1f}) | still truncated: {trunc} | "
143
+ f"avg tokens: {avg_tok:.0f} | acc on finished: {acc_fin:.1f}%")
144
+
145
+ diff = accs["MAX-9B"] - accs["Original"]
146
+ noise = math.sqrt(margin(accs["MAX-9B"], n) ** 2 + margin(accs["Original"], n) ** 2)
147
+ print("-" * 56)
148
+ print(f" Difference (MAX - Original): {diff:+.1f} points (noise โ‰ˆ ยฑ{noise:.1f})")
149
+
150
+ # ู…ู‚ุงุฑู†ุฉ ู…ุฒุฏูˆุฌุฉ ุนู„ู‰ ุงู„ุฃุณุฆู„ุฉ ุงู„ุชูŠ ุฃูƒู…ู„ ููŠู‡ุง ุงู„ู†ู…ูˆุฐุฌุงู† ุงู„ุชููƒูŠุฑ
151
+ both = [i for i in range(n) if all_rec["MAX-9B"][i]["finished"] and all_rec["Original"][i]["finished"]]
152
+ a = sum(all_rec["MAX-9B"][i]["ok"] for i in both)
153
+ b = sum(all_rec["Original"][i]["ok"] for i in both)
154
+ print(f" Paired (both finished, {len(both)} questions): MAX {a / len(both) * 100:.1f}% vs Original {b / len(both) * 100:.1f}%")
155
+ print("=" * 56)
156
+
157
+ if diff > noise:
158
+ print(" Clear improvement over the original.")
159
+ elif diff < -noise:
160
+ print(" Clearly worse than the original.")
161
+ else:
162
+ print(" No statistically clear difference in accuracy.")
163
+ print(" Compare 'avg tokens': a clearly lower value for MAX means shorter reasoning.")