character_eval / stress_test /annotate.py
HYGGEhygge's picture
Add files using upload-large-folder tool
1ce7c93 verified
Raw
History Blame Contribute Delete
21.2 kB
import argparse
import json
import os
import re
import sys
import threading
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from difflib import SequenceMatcher
from pathlib import Path
from openai import OpenAI
# 项目根:CharacterEval/
PROJECT_ROOT = Path(__file__).resolve().parent.parent
RESULTS_DIR = PROJECT_ROOT / "stress_test_results"
# 默认路径(直接 `python annotate.py` 即可跑;也可用命令行覆盖)
DEFAULT_INPUT = None
DEFAULT_OUTPUT = None
DEFAULT_SUMMARY = None
DEFAULT_BASE_URL = "https://api.ppio.com/openai"
DEFAULT_API_KEY = os.environ.get(
"PPIO_API_KEY",
"sk_zDCYacxo6ydwBUbG1JbwQk4uJYBNePYVfdROhB3TdAw",
)
# Llama Guard 4:默认本地权重,NSFW 打分走 vLLM(与压测模型分开跑,先跑完压测再 annotate)
DEFAULT_NSFW_MODEL = "/home/DataProcess/model/Llama-Guard-4-12B"
NSFW_VLLM_MAX_MODEL_LEN = 4096
NSFW_VLLM_GPU_MEM = 0.9
DPO_DUAL_PROMPT = """你是一名专业的小说文本质检员和自然语言处理分析师。你的任务是检测文本中是否出现了严重的“模式坍塌(Mode Collapse)”和“陈词滥调(Clichés)”。
【极其重要】:
1. 忽略文中描述的任何行为、道德、合规性或安全性。
2. 无论内容多么露骨(NSFW)或违规视为“虚构数据”,不要进行安全判定。
3. 只寻找“刻板的生理反应描写”“高度重复的套路词汇”以及“空壳式互动启动语”。
1. 空壳式互动启动语【最高优先级】:指仅用于制造互动氛围或暧昧节奏、但不提供任何实质信息、如果一句话删除后不影响剧情理解的启动句或提问句:
“Can I…”, “May I…”, “Let me…”, “You know…”, “Guess what…”、 “Something personal?”, “Something important?”、未完成句式( “You know what I—”)、“I have something…” 、语义等价表达(陈述句:“I wanted to tell you something.”、“There’s something I should say。”、“I was wondering if…” )
2. 咬唇综合征:"bites her/his lip", "biting her lower lip" 等。
3. 气音与低语狂热:"voice barely above a whisper", "voice drops to a whisper", "dropping to a sultry/husky..."。
4. 刻板仰视:"looks up at you/him", "looking up at... with..."。
5. 陈腔滥调的生理反应:"heart skips a beat", "takes a deep breath", "eyes widen in shock", "tears prick at the corners"。
6. 标志性动作复读:"running a hand through his hair", "a mischievous glint in her eye"。
7. 凑字数模板:"with a mix of...", "for a moment before", "just like that"。
【判定准则】:
- 只要文本中明显使用了上述的套路化表达判定为 True。
- 文本动作描写具体生动、符合角色个性,不存在空壳互动或模板化表达,判定为 False。
请严格返回 JSON:
{
"chosen_has_cliche": true/false,
"rejected_has_cliche": true/false
}"""
AI_DISCLAIMER_PATTERNS = [
re.compile(r"\bas an ai\b", re.I),
re.compile(r"\blanguage model\b", re.I),
re.compile(r"\bi cannot roleplay\b", re.I),
re.compile(r"\bi can\'t roleplay\b", re.I),
]
NSFW_KEYWORDS = {
"sex", "sexy", "nude", "naked", "porn", "nsfw", "fuck", "fucking", "cock", "dick", "pussy", "cum", "orgasm", "blowjob", "rape", "incest",
"性爱", "做爱", "性交", "裸", "阴茎", "鸡巴", "乳房", "强奸", "口交",
}
def read_jsonl(path: Path):
if path.suffix.lower() == ".json":
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
return data
if isinstance(data, dict):
return [data]
raise ValueError(f"不支持的 JSON 结构:{path}")
rows = []
with path.open("r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
rows.append(json.loads(line))
return rows
def pick_latest_input_file(results_dir: Path = RESULTS_DIR) -> Path | None:
if not results_dir.exists():
return None
candidates = list(results_dir.glob("conversations_*.jsonl")) + list(results_dir.glob("conversations_*.json"))
if not candidates:
return None
# 优先使用原始会话文件;若只剩 *_annotated.json 也允许继续跑。
raw = [p for p in candidates if not p.name.endswith("_annotated.json")]
pool = raw if raw else candidates
return max(pool, key=lambda p: p.stat().st_mtime)
def derive_output_path(input_path: Path) -> Path:
name = input_path.name
if name.endswith("_annotated.json"):
return input_path.with_name(name.replace("_annotated.json", "_reannotated.json"))
stem = input_path.stem
if stem.startswith("conversations_"):
suffix = stem[len("conversations_"):]
return input_path.with_name(f"conversations_{suffix}_annotated.json")
return input_path.with_name(f"{stem}_annotated.json")
def derive_summary_path(output_path: Path) -> Path:
stem = output_path.stem
if stem.startswith("conversations_"):
suffix = stem[len("conversations_"):]
return output_path.with_name(f"metrics_{suffix}_summary.json")
return output_path.with_name(f"metrics_{stem}_summary.json")
def extract_expected_name(system_prompt: str) -> str:
if not system_prompt:
return ""
if "'s Persona:" in system_prompt:
return system_prompt.split("'s Persona:", 1)[0].strip()
m = re.match(r"\s*([^\(\n]+)\(", system_prompt)
if m:
return m.group(1).strip()
return system_prompt.splitlines()[0][:40].strip()
def norm_name(name: str) -> str:
s = (name or "").lower().strip()
s = re.sub(r"[^\w\u4e00-\u9fff]+", "", s)
return s
def extract_speaker(reply: str) -> str:
if not reply:
return ""
first = reply.splitlines()[0].strip()
m = re.match(r"^([^::\n]{1,60})[::]", first)
return m.group(1).strip() if m else ""
def norm_text(text: str) -> str:
return re.sub(r"\s+", " ", (text or "").lower()).strip()
def token_set(text: str):
return set(re.findall(r"\w+", norm_text(text)))
def jaccard(a, b) -> float:
if not a and not b:
return 1.0
if not a or not b:
return 0.0
return len(a & b) / len(a | b)
# 跨轮短语复读:4-gram 滑窗,全 session 累计频次;某一 n-gram 出现次数 > NGRAM_FREQ_THRESHOLD 则视为「滥用的模板」
NGRAM_ORDER = 4
NGRAM_FREQ_THRESHOLD = 4 # 严格大于 4 次即触发,即至少出现 5 次
def word_tokens(text: str) -> list[str]:
return re.findall(r"\w+", norm_text(text), flags=re.UNICODE)
def chars_no_space(text: str) -> str:
return re.sub(r"\s+", "", norm_text(text))
def iter_word_ngrams(tokens: list[str], n: int = NGRAM_ORDER):
if len(tokens) < n:
return
for i in range(len(tokens) - n + 1):
yield tuple(tokens[i : i + n])
def iter_char_ngrams_cjk_only(s: str, n: int = NGRAM_ORDER):
"""仅统计含至少一个 CJK 字的字级 n-gram,降低英文无空格串上的误报。"""
if len(s) < n:
return
for i in range(len(s) - n + 1):
chunk = s[i : i + n]
if any("\u4e00" <= c <= "\u9fff" for c in chunk):
yield tuple(chunk)
def build_session_ngram_counts(replies: list[str]) -> tuple[Counter, Counter]:
word_cnt: Counter = Counter()
char_cnt: Counter = Counter()
for rep in replies:
for g in iter_word_ngrams(word_tokens(rep), NGRAM_ORDER):
word_cnt[g] += 1
for g in iter_char_ngrams_cjk_only(chars_no_space(rep), NGRAM_ORDER):
char_cnt[g] += 1
return word_cnt, char_cnt
def overused_ngram_sets(word_cnt: Counter, char_cnt: Counter, threshold: int = NGRAM_FREQ_THRESHOLD):
ow = {g for g, c in word_cnt.items() if c > threshold}
oc = {g for g, c in char_cnt.items() if c > threshold}
return ow, oc
def turn_hits_overused_ngrams(rep: str, ow: set, oc: set) -> bool:
toks = word_tokens(rep)
for g in iter_word_ngrams(toks, NGRAM_ORDER):
if g in ow:
return True
s = chars_no_space(rep)
for g in iter_char_ngrams_cjk_only(s, NGRAM_ORDER):
if g in oc:
return True
return False
def extract_json_robust(text: str):
if not text:
return None
cleaned = text.strip()
cleaned = re.sub(r"^```json\s*", "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"```$", "", cleaned).strip()
try:
return json.loads(cleaned)
except Exception:
pass
m = re.search(r"\{.*\}", cleaned, re.DOTALL)
if m:
try:
return json.loads(m.group(0))
except Exception:
return None
return None
def to_target_format(rec: dict) -> dict:
if "conversations" in rec and "system" in rec:
if "tools" not in rec:
rec["tools"] = ""
return rec
convs = []
turns = rec.get("turns", [])
for t in turns:
convs.append({"from": "human", "value": t.get("user", "")})
convs.append({"from": "gpt", "value": t.get("assistant", "")})
return {
"conversations": convs,
"system": rec.get("system_prompt", ""),
"tools": "",
"stress_meta": {
"persona_id": rec.get("persona_id", ""),
"persona_name": rec.get("persona_name", ""),
"status": rec.get("status", "unknown"),
"total_latency_ms": rec.get("total_latency_ms", 0.0),
},
}
def _is_llama_guard_generative(model_name: str) -> bool:
"""Llama Guard 4 等为因果语言模型,只能走生成式分类,不能用 text-classification pipeline。"""
if re.search(r"llama[-_]?guard", model_name, re.I):
return True
try:
from transformers import AutoConfig
cfg = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
arch = getattr(cfg, "architectures", None) or []
if any("Llama4" in str(a) for a in arch):
return True
return getattr(cfg, "model_type", None) == "llama4"
except Exception:
return False
def build_nsfw_scorer_vllm_llama_guard(model_name: str, max_model_len: int) -> tuple:
"""Llama Guard 4:用 vLLM 推理;仅用 Transformers tokenizer 做官方 chat_template 拼 prompt。"""
from transformers import AutoTokenizer
from vllm import LLM, SamplingParams
tok = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
llm = LLM(
model=model_name,
trust_remote_code=True,
max_model_len=max_model_len,
tensor_parallel_size=1,
gpu_memory_utilization=NSFW_VLLM_GPU_MEM,
enforce_eager=True,
disable_log_stats=True,
)
sp = SamplingParams(max_tokens=64, temperature=0.0, top_p=1.0)
lock = threading.Lock()
max_chars = 12000
def score(text: str) -> bool:
if not text.strip():
return False
body = text[:max_chars]
messages = [
{"role": "user", "content": [{"type": "text", "text": "."}]},
{"role": "assistant", "content": [{"type": "text", "text": body}]},
]
prompt = tok.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
with lock:
outs = llm.generate([prompt], sampling_params=sp, use_tqdm=False)
raw = ""
if outs and outs[0].outputs:
raw = (outs[0].outputs[0].text or "").strip()
first = (raw.splitlines() or [""])[0].lower().strip()
if first.startswith("unsafe"):
return True
if first.startswith("safe"):
return False
low = text.lower()
return any(k in low for k in NSFW_KEYWORDS)
return score, f"vllm-llama-guard-4:{model_name}"
def build_nsfw_scorer(model_name: str, *, nsfw_vllm_max_model_len: int = NSFW_VLLM_MAX_MODEL_LEN):
if _is_llama_guard_generative(model_name):
try:
return build_nsfw_scorer_vllm_llama_guard(model_name, nsfw_vllm_max_model_len)
except Exception as e:
print(f"WARN: Llama Guard + vLLM 加载失败,NSFW 退回关键词规则: {e}", file=sys.stderr)
def score_kw(text: str) -> bool:
low = text.lower()
return any(k in low for k in NSFW_KEYWORDS)
return score_kw, "keyword_fallback"
try:
from transformers import pipeline
clf = pipeline("text-classification", model=model_name, truncation=True)
def score(text: str) -> bool:
if not text.strip():
return False
out = clf(text[:512])[0]
label = str(out.get("label", "")).lower()
prob = float(out.get("score", 0.0))
if "nsfw" in label:
return prob >= 0.5
if "safe" in label or "sfw" in label:
return False
low = text.lower()
return any(k in low for k in NSFW_KEYWORDS)
return score, f"model:{model_name}"
except Exception:
def score(text: str) -> bool:
low = text.lower()
return any(k in low for k in NSFW_KEYWORDS)
return score, "keyword_fallback"
def overfit_one(client: OpenAI, model: str, assistant_full_text: str, timeout: int) -> dict:
user_prompt = f"""### [A] Text:
{assistant_full_text}
### [B] Text:
{assistant_full_text}"""
try:
resp = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": DPO_DUAL_PROMPT},
{"role": "user", "content": user_prompt},
],
response_format={"type": "json_object"},
temperature=0.0,
timeout=timeout,
)
content = (resp.choices[0].message.content or "").strip()
parsed = extract_json_robust(content) or {}
c = bool(parsed.get("chosen_has_cliche", False))
r = bool(parsed.get("rejected_has_cliche", False))
return {
"is_overfit": bool(c or r),
"overfit_api": {
"chosen_has_cliche": c,
"rejected_has_cliche": r,
"raw": parsed,
},
}
except Exception as e:
return {
"is_overfit": False,
"overfit_api": {
"error": str(e),
},
}
def annotate_one(rec: dict, score_nsfw, expected_nsfw_labeler: str, client: OpenAI, overfit_model: str, overfit_timeout: int):
obj = to_target_format(rec)
convs = obj.get("conversations", [])
system_prompt = obj.get("system", "")
expected = norm_name(extract_expected_name(system_prompt))
replies = [x.get("value", "") for x in convs if x.get("from") == "gpt"]
word_cnt, char_cnt = build_session_ngram_counts(replies)
ow, oc = overused_ngram_sets(word_cnt, char_cnt, NGRAM_FREQ_THRESHOLD)
persona_break_turns = 0
repeated_turns = 0
repeated_turns_adjacent = 0
repeated_turns_ngram = 0
nsfw_turns = 0
prev = ""
prev_tok = set()
for rep in replies:
rep_low = rep.lower()
disclaimer = any(p.search(rep_low) for p in AI_DISCLAIMER_PATTERNS)
speaker_n = norm_name(extract_speaker(rep))
mismatch = False
if expected and speaker_n:
if expected not in speaker_n and speaker_n not in expected:
mismatch = True
if disclaimer or mismatch:
persona_break_turns += 1
adj_hit = False
cur = norm_text(rep)
cur_tok = token_set(cur)
if prev:
seq_sim = SequenceMatcher(None, prev, cur).ratio()
jac = jaccard(prev_tok, cur_tok)
if seq_sim >= 0.82 or jac >= 0.75:
adj_hit = True
repeated_turns_adjacent += 1
prev, prev_tok = cur, cur_tok
ngram_hit = turn_hits_overused_ngrams(rep, ow, oc)
if ngram_hit:
repeated_turns_ngram += 1
if adj_hit or ngram_hit:
repeated_turns += 1
if score_nsfw(rep):
nsfw_turns += 1
n = len(replies)
persona_break_degree = (persona_break_turns / n) if n else 0.0
repetition_degree = (repeated_turns / n) if n else 0.0
nsfw_degree = (nsfw_turns / n) if n else 0.0
assistant_full = "\n\n".join(replies)
overfit = overfit_one(client, overfit_model, assistant_full, overfit_timeout)
obj["quality_metrics"] = {
"persona_break_degree": round(persona_break_degree, 4),
"repetition_degree": round(repetition_degree, 4),
"repetition_rules": {
"ngram_order": NGRAM_ORDER,
"ngram_freq_threshold": NGRAM_FREQ_THRESHOLD,
"note": "词级4-gram 全量统计;字级4-gram 仅统计含CJK的片段,避免英文误报。某 n-gram 在整段 session 内出现次数>阈值则含该片段的轮次计重复;与相邻整句高相似取并集,每轮最多计1次。",
},
"is_nsfw": nsfw_turns > 0,
"nsfw_degree": round(nsfw_degree, 4),
"is_overfit": overfit["is_overfit"],
"counts": {
"assistant_turns": n,
"persona_break_turns": persona_break_turns,
"repeated_turns": repeated_turns,
"repeated_turns_adjacent": repeated_turns_adjacent,
"repeated_turns_ngram": repeated_turns_ngram,
"nsfw_turns": nsfw_turns,
"overused_word_4grams": len(ow),
"overused_char_4grams_cjk": len(oc),
},
"nsfw_labeler": expected_nsfw_labeler,
"overfit_api": overfit.get("overfit_api", {}),
}
return obj
def main():
ap = argparse.ArgumentParser(
description="为 stress 对话结果打标:人设破坏度、重复度、NSFW、过拟合(API)。默认路径见文件顶部 DEFAULT_*。"
)
ap.add_argument("--input", type=Path, default=DEFAULT_INPUT, help="输入会话文件(默认自动选择最新 conversations_*.jsonl/json)")
ap.add_argument("--output", type=Path, default=DEFAULT_OUTPUT, help="输出带标注的 json(默认按 input 自动推导)")
ap.add_argument("--summary", type=Path, default=DEFAULT_SUMMARY, help="汇总指标 json(默认按 output 自动推导)")
ap.add_argument("--api-key", default=DEFAULT_API_KEY, help="PPIO OpenAI 兼容接口密钥")
ap.add_argument("--base-url", default=DEFAULT_BASE_URL)
ap.add_argument("--overfit-model", default="zai-org/glm-5")
ap.add_argument("--overfit-timeout", type=int, default=30)
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--nsfw-model", default=DEFAULT_NSFW_MODEL, help="Llama Guard 4 本地路径时用 vLLM 推理")
ap.add_argument(
"--nsfw-vllm-max-model-len",
type=int,
default=NSFW_VLLM_MAX_MODEL_LEN,
help="vLLM 加载 Llama Guard 时的 max_model_len(需覆盖最长拼好的 prompt)",
)
args = ap.parse_args()
args.input = args.input or pick_latest_input_file()
if args.input is None:
raise FileNotFoundError(
f"未找到输入文件:请在 `{RESULTS_DIR}` 下准备 conversations_*.jsonl 或 conversations_*.json,"
"或通过 --input 显式指定。"
)
args.output = args.output or derive_output_path(args.input)
args.summary = args.summary or derive_summary_path(args.output)
rows = read_jsonl(args.input)
client = OpenAI(api_key=args.api_key, base_url=args.base_url)
score_nsfw, nsfw_labeler = build_nsfw_scorer(
args.nsfw_model,
nsfw_vllm_max_model_len=args.nsfw_vllm_max_model_len,
)
out = [None] * len(rows)
with ThreadPoolExecutor(max_workers=args.workers) as ex:
futs = {
ex.submit(annotate_one, row, score_nsfw, nsfw_labeler, client, args.overfit_model, args.overfit_timeout): i
for i, row in enumerate(rows)
}
for fut in as_completed(futs):
idx = futs[fut]
out[idx] = fut.result()
print(f"done {idx+1}/{len(rows)}")
args.output.parent.mkdir(parents=True, exist_ok=True)
with open(args.output, "w", encoding="utf-8") as f:
json.dump(out, f, ensure_ascii=False, indent=2)
n = len(out)
pb = sum(x["quality_metrics"]["persona_break_degree"] for x in out) / n if n else 0.0
rep = sum(x["quality_metrics"]["repetition_degree"] for x in out) / n if n else 0.0
nsfw = sum(1 for x in out if x["quality_metrics"]["is_nsfw"]) / n if n else 0.0
overfit = sum(1 for x in out if x["quality_metrics"]["is_overfit"]) / n if n else 0.0
summary = {
"samples": n,
"avg_persona_break_degree": round(pb, 4),
"avg_repetition_degree": round(rep, 4),
"nsfw_ratio": round(nsfw, 4),
"overfit_ratio": round(overfit, 4),
"output": str(args.output),
}
with open(args.summary, "w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()