File size: 2,497 Bytes
491e16d
 
 
 
 
 
 
 
 
 
 
 
 
 
16b1b18
 
 
 
491e16d
16b1b18
 
 
491e16d
16b1b18
 
491e16d
16b1b18
 
 
491e16d
16b1b18
491e16d
16b1b18
 
 
 
 
 
 
 
 
 
 
 
491e16d
16b1b18
 
 
491e16d
16b1b18
 
 
 
 
 
 
 
 
 
491e16d
16b1b18
 
 
 
491e16d
16b1b18
 
 
 
 
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
65
66
67
68
69
70
71
# /// 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: <number>'\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()