# -*- coding: utf-8 -*- """Round2 评测:身份认同 + 好奇心 + 领域能力不回归。 关键设计: - must_include 必须出现(全部) - must_include_any 至少出现一个 - must_not_include 绝对不能出现(反向探针:防止"说反了还满分") - followup 是否检测"给出真正值得追问的问题"(末尾含问号且长度合理) 用法: venv\\Scripts\\python.exe scripts\\eval_round2.py --adapter """ import argparse import json import os import re from pathlib import Path ROOT = Path(__file__).resolve().parent.parent os.chdir(ROOT) ap = argparse.ArgumentParser() ap.add_argument("--adapter", default=str(ROOT / "output" / "round2_stage2" / "adapter")) ap.add_argument("--base", default=str(ROOT / "models" / "Qwen3-8B")) ap.add_argument("--questions", default=str(ROOT / "scripts" / "eval_questions_round2.json")) ap.add_argument("--out", default=str(ROOT / "output" / "eval_round2_results.json")) args = ap.parse_args() from unsloth import FastLanguageModel # noqa: E402 from peft import PeftModel # noqa: E402 import torch # noqa: E402 import sys as _sys _sys.path.insert(0, str(ROOT / "scripts")) from prompt import SYSTEM_PROMPT as SYSTEM # noqa: E402 print("[eval] 加载模型...", flush=True) model, tokenizer = FastLanguageModel.from_pretrained( model_name=args.base, max_seq_length=4096, dtype=None, load_in_4bit=True, ) model = PeftModel.from_pretrained(model, args.adapter) FastLanguageModel.for_inference(model) print("[eval] 就绪", flush=True) questions = json.loads(Path(args.questions).read_text(encoding="utf-8")) results = [] for q in questions: msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": q["q"]}] prompt = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) inputs = tokenizer(prompt, return_tensors="pt").to("cuda") out = model.generate( **inputs, max_new_tokens=1536, temperature=0.7, do_sample=True, top_p=0.9, repetition_penalty=1.1, ) ans = tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip() ans = re.sub(r".*?", "", ans, flags=re.DOTALL).strip() checks = {} for t in q.get("must_include", []): checks[f"inc:{t}"] = (t in ans) for t in q.get("must_include_any", []): checks[f"any:{t}"] = (t in ans) # 同义词组:must_include_synonyms = [["分箱","binning"], ...] 组内任一命中即算该组通过 syn_groups = q.get("must_include_synonyms", []) syn_pass = True for gi, group in enumerate(syn_groups): hit = any((t in ans) for t in group) checks[f"syn{gi}:{'|'.join(group)}"] = hit syn_pass = syn_pass and hit for t in q.get("must_not_include", []): checks[f"NOT:{t}"] = (t not in ans) # 追问检测:末尾 200 字里有问号 tail = ans[-200:] checks["followup"] = ("?" in tail or "?" in tail) # 硬门槛:所有 must_include / 同义词组 / must_not_include 必须过 hard_pass = all(v for k, v in checks.items() if k.startswith("inc:") or k.startswith("NOT:") or k.startswith("syn")) any_keys = [k for k in checks if k.startswith("any:")] any_pass = (not any_keys) or any(checks[k] for k in any_keys) score = hard_pass and any_pass results.append({ "id": q["id"], "type": q["type"], "question": q["q"], "answer": ans, "checks": checks, "hard_pass": hard_pass, "any_pass": any_pass, "score": score, "note": q.get("note", ""), }) flag = "PASS" if score else "FAIL" print(f"[{flag}] {q['id']} ({q['type']}) {q['q'][:40]}", flush=True) if not score: bad = [k for k, v in checks.items() if (k.startswith("inc:") or k.startswith("NOT:")) and not v] print(f" 未满足: {bad}", flush=True) Path(args.out).write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8") by_type = {} for r in results: t = by_type.setdefault(r["type"], [0, 0]) t[0] += 1 t[1] += 1 if r["score"] else 0 print("\n===== 汇总 =====") for k, (tot, ok) in sorted(by_type.items()): print(f" {k:10s}: {ok}/{tot} = {ok/tot:.0%}") tot = len(results) ok = sum(1 for r in results if r["score"]) print(f" {'TOTAL':10s}: {ok}/{tot} = {ok/tot:.0%}") fu = sum(1 for r in results if r["type"] == "curiosity" and r["checks"].get("followup")) cur = sum(1 for r in results if r["type"] == "curiosity") print(f" 好奇心题末尾带追问: {fu}/{cur}") print(f"\n结果 -> {args.out}")