- models/{small_model,large_model,large_model_lora} 整树入库,权重/分词器走 Git LFS(约 17 GB)
- .gitattributes 改用 models/** 通配;.gitignore 放行 models 下的 tokenizer_config.json
- config: llm[].file 指向 models/small_model,删除含 qwen3 的注释
- docs/plugins.md、tests/test_config.py 同步新路径;LoRA 卡去掉 base_model 私有路径字段
- 补入 intent_bench / shieldagent_review / result.json 等实验脚本与结果
166 lines
7.4 KiB
Python
166 lines
7.4 KiB
Python
# -*- coding: utf-8 -*-
|
|
r"""官方 Qwen3GuardTest 全流程: 模型检测(断点续跑) -> 导出失败样本为 SFT 训练数据
|
|
运行: python3 212.py (默认跑 thinking, response_loc, thinking_loc 三个 split)
|
|
python3 212.py thinking_loc (只跑指定 split)
|
|
"""
|
|
import os, sys, json, re, time, random
|
|
from collections import defaultdict
|
|
|
|
# ===== 路径: 锚定脚本所在目录 =====
|
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
def p(*x): return os.path.join(BASE_DIR, *x)
|
|
|
|
DATA_DIR = p("qwen3guard_test")
|
|
MODEL_PATH = p("model")
|
|
RESULT_DIR = p("official_results")
|
|
OUT_DIR = p("train_data")
|
|
os.makedirs(RESULT_DIR, exist_ok=True)
|
|
os.makedirs(OUT_DIR, exist_ok=True)
|
|
|
|
SPLITS = sys.argv[1:] if len(sys.argv) > 1 else ["thinking", "response_loc", "thinking_loc"]
|
|
MAX_RESP_TOKENS = 1024 # thinking split 截断
|
|
MAX_NEW_TOKENS = 128
|
|
random.seed(42)
|
|
|
|
# ==================== 加载模型 (有CUDA用CUDA) ====================
|
|
os.environ["HF_HUB_OFFLINE"] = "1"; os.environ["TRANSFORMERS_OFFLINE"] = "1"
|
|
import torch
|
|
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
print(f"使用设备: {device}" + (f" ({torch.cuda.get_device_name(0)})" if device == "cuda" else ""))
|
|
|
|
print(f"加载模型 {MODEL_PATH} ...")
|
|
tok = AutoTokenizer.from_pretrained(MODEL_PATH)
|
|
if tok.pad_token is None: tok.pad_token = tok.eos_token
|
|
if device == "cuda":
|
|
model = AutoModelForCausalLM.from_pretrained(
|
|
MODEL_PATH, dtype=torch.bfloat16, device_map="cuda")
|
|
else:
|
|
model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, dtype=torch.float32)
|
|
model.eval()
|
|
print("模型加载完成\n")
|
|
|
|
SAFE_PAT = re.compile(r"Safety: (Safe|Unsafe|Controversial)")
|
|
|
|
def truncate_asst(text, n):
|
|
ids = tok(text, add_special_tokens=False).input_ids
|
|
return tok.decode(ids[:n], skip_special_tokens=False)
|
|
|
|
def classify(msgs):
|
|
text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
|
|
inputs = tok([text], return_tensors="pt").to(model.device)
|
|
with torch.inference_mode():
|
|
out = model.generate(**inputs, max_new_tokens=MAX_NEW_TOKENS,
|
|
do_sample=False, pad_token_id=tok.pad_token_id)
|
|
gen = tok.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
|
|
m = SAFE_PAT.search(gen)
|
|
return (m.group(1) if m else "error")
|
|
|
|
# ==================== 阶段 1: 检测并落盘 (断点续跑) ====================
|
|
orig = {}
|
|
for sp in SPLITS:
|
|
fp = p(DATA_DIR, f"{sp}.jsonl")
|
|
if not os.path.exists(fp):
|
|
print(f"[警告] 缺数据集 {fp}, 跳过"); continue
|
|
rows = [json.loads(l) for l in open(fp, encoding="utf-8") if l.strip()]
|
|
for r in rows: orig[r["unique_id"]] = {"split": sp, **r}
|
|
|
|
out_path = p(RESULT_DIR, f"{sp}_results.jsonl")
|
|
done = set()
|
|
if os.path.exists(out_path): # 断点续跑
|
|
for l in open(out_path, encoding="utf-8"):
|
|
if l.strip(): done.add(json.loads(l)["id"])
|
|
todo = [r for r in rows if r["unique_id"] not in done]
|
|
print(f"[{sp}] 共 {len(rows)} 条, 已完成 {len(done)}, 本次待跑 {len(todo)}")
|
|
if not todo:
|
|
continue
|
|
|
|
t0, n_done = time.time(), 0
|
|
with open(out_path, "a", encoding="utf-8") as f:
|
|
for i, r in enumerate(todo, 1):
|
|
user, asst = r["message"][0]["content"], r["message"][-1]["content"]
|
|
if sp in ("response_loc", "thinking_loc"):
|
|
idx = r.get("unsafe_start_index")
|
|
asst = truncate_asst(asst, idx if idx is not None else 512)
|
|
else:
|
|
asst = truncate_asst(asst, MAX_RESP_TOKENS)
|
|
pred = classify([{"role": "user", "content": user},
|
|
{"role": "assistant", "content": asst}])
|
|
gold = r.get("safety_label") or r.get("gold") or r.get("label")
|
|
f.write(json.dumps({"id": r["unique_id"], "gold": gold, "pred": pred},
|
|
ensure_ascii=False) + "\n")
|
|
f.flush()
|
|
n_done += 1
|
|
if n_done % 20 == 0:
|
|
eta = (time.time() - t0) / n_done * (len(todo) - n_done)
|
|
print(f" {i}/{len(todo)} 剩 {eta/60:.0f} 分", flush=True)
|
|
res = [json.loads(l) for l in open(out_path, encoding="utf-8") if l.strip()]
|
|
acc = sum(r["pred"] == r["gold"] for r in res) / len(res)
|
|
print(f"[{sp}] 完成 Acc={acc:.1%} ({len(res)} 条)\n")
|
|
|
|
# ==================== 阶段 2: 导出失败样本 ====================
|
|
TARGET_UNSAFE = "Safety: Unsafe\nSunsafe Types: {ut}\nResolution: Reject"
|
|
TARGET_SAFE = "Safety: Safe\nSunsafe Types: None"
|
|
|
|
stats = defaultdict(int)
|
|
missed, false_, pool = [], [], []
|
|
for sp in SPLITS:
|
|
rp = p(RESULT_DIR, f"{sp}_results.jsonl")
|
|
if not os.path.exists(rp):
|
|
print(f"[跳过] 无结果文件 {rp}"); continue
|
|
for l in open(rp, encoding="utf-8"):
|
|
if not l.strip(): continue
|
|
r = json.loads(l)
|
|
o = orig.get(r["id"])
|
|
if o is None: stats["原始数据缺失"] += 1; continue
|
|
user, asst = o["message"][0]["content"], o["message"][-1]["content"]
|
|
if sp in ("response_loc", "thinking_loc"):
|
|
idx = o.get("unsafe_start_index")
|
|
asst = truncate_asst(asst, idx if idx is not None else 512)
|
|
else:
|
|
asst = truncate_asst(asst, MAX_RESP_TOKENS)
|
|
item = {"id": f"{sp}/{r['id']}", "split": sp,
|
|
"unsafe_type": o.get("unsafe_type"),
|
|
"messages": [{"role": "user", "content": user},
|
|
{"role": "assistant", "content": asst}]}
|
|
if r["pred"] != r["gold"] and r["pred"] in ("Safe", "Unsafe"):
|
|
if r["gold"] == "Unsafe": # 漏判 -> 教拦截
|
|
item["failure_type"] = "missed_unsafe"
|
|
item["target"] = TARGET_UNSAFE.format(
|
|
ut=o.get("unsafe_type") or "Unethical Acts")
|
|
missed.append(item)
|
|
else: # 误报 -> 教放行
|
|
item["failure_type"] = "false_safe"
|
|
item["target"] = TARGET_SAFE
|
|
false_.append(item)
|
|
stats[f"{sp}/失败"] += 1
|
|
elif r["pred"] == r["gold"] == "Safe": # 判对的 Safe -> 对照池
|
|
item["failure_type"] = "correct_safe_control"
|
|
item["target"] = TARGET_SAFE
|
|
pool.append(item)
|
|
|
|
random.shuffle(pool)
|
|
controls = pool[:int(len(missed) * 1.5)]
|
|
all_out = missed + false_ + controls
|
|
random.shuffle(all_out)
|
|
|
|
out_file = p(OUT_DIR, "official_failures_sft.jsonl")
|
|
with open(out_file, "w", encoding="utf-8") as f:
|
|
for x in all_out:
|
|
f.write(json.dumps(x, ensure_ascii=False) + "\n")
|
|
|
|
# ==================== 统计报告 ====================
|
|
lines = [f"漏判 (gold=Unsafe 判 Safe, 教拦截): {len(missed)}",
|
|
f"误报 (gold=Safe 判 Unsafe, 教放行): {len(false_)}",
|
|
f"放行对照 (判对的 Safe, 防过拦): {len(controls)}",
|
|
f"导出合计: {len(all_out)}", "", "--- 按 split ---"]
|
|
for k, v in sorted(stats.items()): lines.append(f" {k}: {v}")
|
|
lines += ["", "--- 漏判按 unsafe_type ---"]
|
|
g = defaultdict(int)
|
|
for x in missed: g[x["unsafe_type"] or "None"] += 1
|
|
for k, v in sorted(g.items(), key=lambda t: -t[1]): lines.append(f" {k}: {v}")
|
|
report = "\n".join(lines)
|
|
open(p(OUT_DIR, "official_failures_stats.txt"), "w", encoding="utf-8").write(report)
|
|
print("\n" + "=" * 60 + "\n" + report + f"\n\n已写入: {out_file}")
|