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