andyz321 commited on
Commit
90a630e
·
verified ·
1 Parent(s): a986417

Upload scripts/eval_round2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/eval_round2.py +111 -0
scripts/eval_round2.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Round2 评测:身份认同 + 好奇心 + 领域能力不回归。
3
+
4
+ 关键设计:
5
+ - must_include 必须出现(全部)
6
+ - must_include_any 至少出现一个
7
+ - must_not_include 绝对不能出现(反向探针:防止"说反了还满分")
8
+ - followup 是否检测"给出真正值得追问的问题"(末尾含问号且长度合理)
9
+
10
+ 用法:
11
+ venv\\Scripts\\python.exe scripts\\eval_round2.py --adapter <dir>
12
+ """
13
+ import argparse
14
+ import json
15
+ import os
16
+ import re
17
+ from pathlib import Path
18
+
19
+ ROOT = Path(__file__).resolve().parent.parent
20
+ os.chdir(ROOT)
21
+
22
+ ap = argparse.ArgumentParser()
23
+ ap.add_argument("--adapter", default=str(ROOT / "output" / "round2_stage2" / "adapter"))
24
+ ap.add_argument("--base", default=str(ROOT / "models" / "Qwen3-8B"))
25
+ ap.add_argument("--questions", default=str(ROOT / "scripts" / "eval_questions_round2.json"))
26
+ ap.add_argument("--out", default=str(ROOT / "output" / "eval_round2_results.json"))
27
+ args = ap.parse_args()
28
+
29
+ from unsloth import FastLanguageModel # noqa: E402
30
+ from peft import PeftModel # noqa: E402
31
+ import torch # noqa: E402
32
+ import sys as _sys
33
+
34
+ _sys.path.insert(0, str(ROOT / "scripts"))
35
+ from prompt import SYSTEM_PROMPT as SYSTEM # noqa: E402
36
+
37
+ print("[eval] 加载模型...", flush=True)
38
+ model, tokenizer = FastLanguageModel.from_pretrained(
39
+ model_name=args.base, max_seq_length=4096, dtype=None, load_in_4bit=True,
40
+ )
41
+ model = PeftModel.from_pretrained(model, args.adapter)
42
+ FastLanguageModel.for_inference(model)
43
+ print("[eval] 就绪", flush=True)
44
+
45
+ questions = json.loads(Path(args.questions).read_text(encoding="utf-8"))
46
+ results = []
47
+ for q in questions:
48
+ msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": q["q"]}]
49
+ prompt = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
50
+ inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
51
+ out = model.generate(
52
+ **inputs, max_new_tokens=1536, temperature=0.7, do_sample=True, top_p=0.9,
53
+ repetition_penalty=1.1,
54
+ )
55
+ ans = tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
56
+ ans = re.sub(r"<think>.*?</think>", "", ans, flags=re.DOTALL).strip()
57
+
58
+ checks = {}
59
+ for t in q.get("must_include", []):
60
+ checks[f"inc:{t}"] = (t in ans)
61
+ for t in q.get("must_include_any", []):
62
+ checks[f"any:{t}"] = (t in ans)
63
+ # 同义词组:must_include_synonyms = [["分箱","binning"], ...] 组内任一命中即算该组通过
64
+ syn_groups = q.get("must_include_synonyms", [])
65
+ syn_pass = True
66
+ for gi, group in enumerate(syn_groups):
67
+ hit = any((t in ans) for t in group)
68
+ checks[f"syn{gi}:{'|'.join(group)}"] = hit
69
+ syn_pass = syn_pass and hit
70
+ for t in q.get("must_not_include", []):
71
+ checks[f"NOT:{t}"] = (t not in ans)
72
+
73
+ # 追问检测:末尾 200 字里有问号
74
+ tail = ans[-200:]
75
+ checks["followup"] = ("?" in tail or "?" in tail)
76
+
77
+ # 硬门槛:所有 must_include / 同义词组 / must_not_include 必须过
78
+ hard_pass = all(v for k, v in checks.items() if k.startswith("inc:") or k.startswith("NOT:") or k.startswith("syn"))
79
+ any_keys = [k for k in checks if k.startswith("any:")]
80
+ any_pass = (not any_keys) or any(checks[k] for k in any_keys)
81
+ score = hard_pass and any_pass
82
+
83
+ results.append({
84
+ "id": q["id"], "type": q["type"], "question": q["q"],
85
+ "answer": ans, "checks": checks,
86
+ "hard_pass": hard_pass, "any_pass": any_pass, "score": score,
87
+ "note": q.get("note", ""),
88
+ })
89
+ flag = "PASS" if score else "FAIL"
90
+ print(f"[{flag}] {q['id']} ({q['type']}) {q['q'][:40]}", flush=True)
91
+ if not score:
92
+ bad = [k for k, v in checks.items() if (k.startswith("inc:") or k.startswith("NOT:")) and not v]
93
+ print(f" 未满足: {bad}", flush=True)
94
+
95
+ Path(args.out).write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8")
96
+
97
+ by_type = {}
98
+ for r in results:
99
+ t = by_type.setdefault(r["type"], [0, 0])
100
+ t[0] += 1
101
+ t[1] += 1 if r["score"] else 0
102
+ print("\n===== 汇总 =====")
103
+ for k, (tot, ok) in sorted(by_type.items()):
104
+ print(f" {k:10s}: {ok}/{tot} = {ok/tot:.0%}")
105
+ tot = len(results)
106
+ ok = sum(1 for r in results if r["score"])
107
+ print(f" {'TOTAL':10s}: {ok}/{tot} = {ok/tot:.0%}")
108
+ fu = sum(1 for r in results if r["type"] == "curiosity" and r["checks"].get("followup"))
109
+ cur = sum(1 for r in results if r["type"] == "curiosity")
110
+ print(f" 好奇心题末尾带追问: {fu}/{cur}")
111
+ print(f"\n结果 -> {args.out}")