Download eval_gsm8k_custom.py from oExz/temp-eval-scripts: direct link, hf CLI and curl.
- Browser
- Download file 2.15 kB
-
https://huggingface.co/oExz/temp-eval-scripts/resolve/main/eval_gsm8k_custom.py
- Command line
-
hf download hf://oExz/temp-eval-scripts/eval_gsm8k_custom.py
-
curl -L -o eval_gsm8k_custom.py https://huggingface.co/oExz/temp-eval-scripts/resolve/main/eval_gsm8k_custom.py
2.15 kB
| # /// 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}%") | |