# /// script # requires-python = ">=3.10" # dependencies = [ # "datasets", # "vllm>=0.4.0", # "torch>=2.0.0", # "transformers>=4.40.0", # "huggingface-hub", # ] # /// import os import re def main(): from datasets import load_dataset from vllm import LLM, SamplingParams from transformers import AutoTokenizer 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} with vLLM...") tok = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=True) llm = LLM(model=MODEL, trust_remote_code=True, dtype="half", gpu_memory_utilization=0.9) sys_msg = "You are a helpful assistant that solves math problems step by step." problems = [] answers = [] for ex in ds: msgs = [ {"role": "system", "content": sys_msg}, {"role": "user", "content": f"Solve this math problem step by step. End your answer with 'ANSWER: '\n\n{ex['question']}"}, ] formatted = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) problems.append(formatted) 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] answers.append(gt) print(f"Generating answers for {len(problems)} problems...") sampling_params = SamplingParams(temperature=0.0, max_tokens=512, stop=["<|im_end|>", "<|endoftext|>"]) outputs = llm.generate(problems, sampling_params) correct = 0 total = len(outputs) for i, output in enumerate(outputs): gen = output.outputs[0].text.strip() 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 == answers[i]: correct += 1 if i < 5 or i % 50 == 0: print(f"Q{i+1}: GT={answers[i]} Pred={pred} OK={pred==answers[i]}") accuracy = correct / total * 100 print(f"\nGSM8K: {correct}/{total} = {accuracy:.2f}%") if __name__ == "__main__": main()