Download scripts/eval_math500_base.py from tysgydke/Qwen3-4B-LoopIntervention: direct link, hf CLI and curl.
- Browser
- Download file 3.31 kB
-
https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/eval_math500_base.py
- Command line
-
hf download hf://tysgydke/Qwen3-4B-LoopIntervention/scripts/eval_math500_base.py
-
curl -L -o eval_math500_base.py https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/eval_math500_base.py
3.31 kB
| # base 无干预 MATH-500 基线:HF 原生 generate(KV cache,快),thinking on,cap 1024 | |
| # 提取器与 eval_math500.py 完全一致(对比口径相同) | |
| import json, re, sys, time | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| MODEL = '/root/autodl-tmp/models/Qwen/Qwen3-4B' | |
| CKPT = sys.argv[1] if len(sys.argv) > 1 else 'base' | |
| CAP = int(sys.argv[2]) if len(sys.argv) > 2 else 1024 | |
| N = int(sys.argv[3]) if len(sys.argv) > 3 else 60 | |
| ROWS = [json.loads(l) for l in open('/root/autodl-tmp/data/math500/test.jsonl')] | |
| def norm_num(s): | |
| s = s.strip().replace(',', '').replace('\\\\', '\\').replace('\\!', '') | |
| s = re.sub(r'\\left|\\right|\\!|\\,|\\;|\\ ', '', s) | |
| m = re.fullmatch(r'(-?[\d\.]+)(cm|m|km|in|ft|degrees?|\\%)?', s, re.I) | |
| if m: | |
| try: | |
| return float(m.group(1)) | |
| except ValueError: | |
| return None | |
| return None | |
| def equiv(pred, gold): | |
| if pred is None: | |
| return False | |
| p, g = pred.strip(), gold.strip() | |
| if p == g: | |
| return True | |
| np_, ng = norm_num(p), norm_num(g) | |
| if np_ is not None and ng is not None: | |
| return abs(np_ - ng) < 1e-6 | |
| return False | |
| def pred_answer(text): | |
| if '</think>' in text: | |
| text = text.split('</think>')[-1] | |
| cands = [] | |
| for m in re.finditer(r'\\boxed\{([^{}]+)\}', text): | |
| cands.append(m.group(1)) | |
| m = re.search(r'####\s*(.+)', text) | |
| if m: | |
| cands.append(m.group(1).strip()) | |
| m = re.search(r'(?:answer|final answer)\s*(?:is|=|:)\s*\$?([^\s\.\$]+)', text, re.I) | |
| if m: | |
| cands.append(m.group(1)) | |
| nums = re.findall(r'-?\d+\.?\d*', text) | |
| if nums: | |
| cands.append(nums[-1]) | |
| return cands[0] if cands else None | |
| def main(): | |
| tok = AutoTokenizer.from_pretrained(MODEL) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL, dtype=torch.bfloat16).cuda().eval() | |
| probs = [(r['problem'], r['answer']) for r in ROWS[:N]] | |
| correct, n, t0 = 0, 0, time.time() | |
| rows_out = [] | |
| for i, (q, gold) in enumerate(probs): | |
| msgs = [{"role": "user", "content": q}] | |
| text = tok.apply_chat_template(msgs, tokenize=False, | |
| add_generation_prompt=True, | |
| enable_thinking=True) | |
| enc = tok(text, return_tensors='pt').to('cuda') | |
| out_ids = model.generate( | |
| **enc, max_new_tokens=CAP, do_sample=False, | |
| pad_token_id=tok.eos_token_id) | |
| out = tok.decode(out_ids[0, enc['input_ids'].shape[1]:]) | |
| pred = pred_answer(out) | |
| ok = equiv(pred, gold) | |
| correct += ok; n += 1 | |
| rows_out.append({'i': i, 'pred': pred, 'gold': gold, 'ok': bool(ok), | |
| 'ntok': out_ids.shape[1] - enc['input_ids'].shape[1], | |
| 'text': out}) | |
| if (i + 1) % 10 == 0: | |
| print(f'base: {i+1}/{n} acc={correct/n:.3f} ' | |
| f'({(time.time()-t0)/n:.1f}s/题)', flush=True) | |
| acc = correct / n | |
| tag = f'math500_base_cap{CAP}_n{n}' | |
| print(json.dumps({'final': tag, 'acc': acc, 'n': n}), flush=True) | |
| with open(f'/root/loop-exp/{tag}.jsonl', 'w') as f: | |
| for row in rows_out: | |
| f.write(json.dumps(row, ensure_ascii=False) + '\n') | |
| if __name__ == '__main__': | |
| main() | |