Datasets:
File size: 17,774 Bytes
2e42639 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 | """与 run_ragtruth.py 对齐的幻觉 span 评估与解析逻辑(供 eval 脚本复用)。"""
from __future__ import annotations
import collections
import json
import re
import traceback
from typing import Any, Dict, List, Optional, Sequence, Tuple
import json_repair
from openai import OpenAI
import threading
_thread_local = threading.local()
_client_lock = threading.Lock()
_shared_clients = {}
def _get_openai_client(model_url: str) -> OpenAI:
"""Reuse OpenAI/httpx clients to avoid FD exhaustion under thread pools."""
with _client_lock:
client = _shared_clients.get(model_url)
if client is None:
client = OpenAI(api_key="EMPTY", base_url=model_url, timeout=None)
_shared_clients[model_url] = client
return client
MODEL_URL = "http://localhost:7010/v1"
TASK_TYPE_TO_INSTRUCTION = {
"QA": "answer",
"Data2txt": "article",
"Summary": "summary",
}
SAVE_DIR = "test_result_0506"
extra_sft_prompt_reasoning = """Your task is to determine whether the <|task_word|> contains hallucinations. First, provide reasoning with the following format:
## Step 1: < your first reasoning step >
## Step 2: < your next reasoning step >
...(add as many steps as needed)
Then, compile the labeled hallucinated spans into a JSON dict, with a key hallucination list and its value is a list of hallucinated spans. If there are potential hallucinations, the output should be in the following JSON format: {"hallucination list": [hallucination span1, hallucination span2, ...]}. Otherwise, leave the value as an empty list as follows: {"hallucination list": []}."""
extra_sft_prompt = """Your task is to determine whether the <|task_word|> contains hallucinations. Then, compile the labeled hallucinated spans into a JSON dict, with a key hallucination list and its value is a list of hallucinated spans. If there are potential hallucinations, the output should be in the following JSON format: {"hallucination list": [hallucination span1, hallucination span2, ...]}. Otherwise, leave the value as an empty list as follows: {"hallucination list": []}."""
# 格式错误重试相关常量:首次 attempt 用 temperature=0(贪心、可复现),
# 第 2/3 次重试切到 RETRY_TEMPERATURE 引入随机性以摆脱反复输出错误格式。
MAX_GEN_ATTEMPTS = 3
RETRY_TEMPERATURE = 0.4
_HALLU_LIST_REGEX = re.compile(r"""{"hallucination list": \[.*?\]}""")
def _format_is_ok(output_str: str) -> bool:
"""
与 ``parse_output`` 等价的"格式校验"快速通道:
1) 至少要能匹配到一个 ``{"hallucination list": [...]}`` 片段;
2) 取最后一个片段经 ``json_repair`` 解析后,必须是含 ``hallucination list`` 键的 dict 或本身是 list。
任一条不满足则视为格式错误,调用方据此决定是否重试。
"""
if not isinstance(output_str, str) or not output_str:
return False
matches = _HALLU_LIST_REGEX.findall(output_str)
if not matches:
return False
try:
parsed = json_repair.loads(matches[-1])
except Exception:
return False
if isinstance(parsed, dict) and "hallucination list" in parsed:
return True
if isinstance(parsed, list):
return True
return False
def req_model_vllm_with_finish_reason(
query: str,
model_name: str,
model_url: str = MODEL_URL,
max_tokens: int = 4000,
temperature: float = 0.0,
) -> Tuple[str, Optional[str]]:
"""
与 ``req_model_vllm`` 相同请求,额外返回 vLLM/OpenAI 兼容的 ``finish_reason``(如 ``stop``、``length``)。
请求失败时返回 ``(错误信息字符串, None)``。``temperature`` 用于重试时切换采样温度。
"""
try:
client = _get_openai_client(model_url)
chat_response = client.chat.completions.create(
model=model_name,
messages=[{"role": "user", "content": query}],
max_tokens=max_tokens,
temperature=temperature,
top_p=0.95,
extra_body={
"stop": ["<|im_end|>"],
"top_k": -1,
"repetition_penalty": 1.0,
},
)
except Exception as e:
traceback.print_exc()
return str(e), None
choice = chat_response.choices[0]
content = choice.message.content
if content is None:
content = ""
fr = getattr(choice, "finish_reason", None)
return content, fr
def req_model_vllm(
query: str,
model_name: str,
model_url: str = MODEL_URL,
max_tokens: int = 4000,
max_attempts: int = MAX_GEN_ATTEMPTS,
retry_temperature: float = RETRY_TEMPERATURE,
) -> str:
"""
请求模型并在格式错误时重试:
- 第 1 次 attempt 使用 temperature=0;后续重试使用 ``retry_temperature``(默认 0.4)。
- 通过 ``_format_is_ok`` 检查是否包含可解析的 ``{"hallucination list": [...]}`` 片段。
- 至多尝试 ``max_attempts`` 次(含首次),仍失败则返回最后一次的原始内容(交由下游 ``parse_output`` 兜底为 ``[]``)。
"""
last_content = ""
attempts = max(1, int(max_attempts))
for attempt in range(1, attempts + 1):
temperature = 0.0 if attempt == 1 else float(retry_temperature)
content, _ = req_model_vllm_with_finish_reason(
query,
model_name,
model_url,
max_tokens=max_tokens,
temperature=temperature,
)
last_content = content
if _format_is_ok(content):
return content
if attempt < attempts:
print(
f"[req_model_vllm] format invalid on attempt {attempt}/{attempts}, "
f"retrying with temperature={retry_temperature}."
)
return last_content
def compute_multi_spans(
gold_spans: Sequence[Tuple[int, int]], pred_spans: Sequence[Tuple[int, int]]
) -> Tuple[int, int, int]:
gold_sets = [set(range(int(start), int(end))) for start, end in gold_spans]
pred_sets = [set(range(int(start), int(end))) for start, end in pred_spans]
gold_union = set.union(*gold_sets) if gold_sets else set()
pred_union = set.union(*pred_sets) if pred_sets else set()
tp = len(gold_union.intersection(pred_union))
pred_len = len(pred_union)
gold_len = len(gold_union)
return tp, pred_len, gold_len
def find_start_end_index(response: str, output: str, strict: bool = False) -> Tuple[int, int]:
response = response.lower()
sub_str = output.lower().strip()
start = response.find(sub_str)
if start == -1:
if len(sub_str) >= 10 and not strict:
match_length = 10
prefix_match = response.find(sub_str[:match_length])
suffix_match = response.find(sub_str[-match_length:])
new_start, new_end = prefix_match, suffix_match + match_length
if (
prefix_match != -1
and suffix_match != -1
and 0.7 < (new_end - new_start) / len(sub_str) < 1.3
):
return new_start, new_end
sub_str = " ".join(sub_str.split())
start = response.find(sub_str)
if start == -1:
return -1, -1
end = start + len(sub_str)
return (start, end)
def cal_metrics(
response: str,
labels: List[Dict[str, Any]],
output_list: List[str],
) -> Tuple[int, int, int, int, int, int, int]:
predict_span = []
for output in output_list:
if not isinstance(output, str):
continue
tup = find_start_end_index(response, output, strict=False)
if tup != (-1, -1):
predict_span.append(tup)
ground_truth_span = []
for label in labels:
tup = (label["start"], label["end"])
ground_truth_span.append(tup)
if len(predict_span) == 0:
predict_span.append((0, 0))
if len(ground_truth_span) == 0:
ground_truth_span.append((0, 0))
match_size, prediction, groud_truth = compute_multi_spans(
ground_truth_span, predict_span
)
pos_true_cnt, neg_true_cnt, neg_false_cnt, pos_false_cnt = 0, 0, 0, 0
if output_list != [] and labels != []:
pos_true_cnt += 1
elif output_list == [] and labels != []:
neg_true_cnt += 1
elif output_list == [] and labels == []:
neg_false_cnt += 1
elif output_list != [] and labels == []:
pos_false_cnt += 1
else:
raise Exception("Error! output: {} labels: {}".format(output_list, labels))
return (
match_size,
prediction,
groud_truth,
pos_true_cnt,
neg_true_cnt,
neg_false_cnt,
pos_false_cnt,
)
def print_metrics(task_cur: str, record: Dict[str, Any]) -> Dict[str, Any]:
record["recall" + task_cur] = (
record["match_size_" + task_cur] / record["groud_truth_" + task_cur]
if record["groud_truth_" + task_cur]
else 0
)
record["precision" + task_cur] = (
record["match_size_" + task_cur] / record["prediction_" + task_cur]
if record["prediction_" + task_cur]
else 0
)
record["f1" + task_cur] = (
2
* record["recall" + task_cur]
* record["precision" + task_cur]
/ (record["recall" + task_cur] + record["precision" + task_cur])
if (record["recall" + task_cur] + record["precision" + task_cur]) > 0
else 0
)
char_res = "span_level:\nprecision: {:.4f}, recall: {:.4f}, f1: {:.4f}".format(
record["precision" + task_cur],
record["recall" + task_cur],
record["f1" + task_cur],
)
record["case_recall_" + task_cur] = (
record["pos_true_cnt_" + task_cur]
/ (record["pos_true_cnt_" + task_cur] + record["neg_true_cnt_" + task_cur])
if (record["pos_true_cnt_" + task_cur] + record["neg_true_cnt_" + task_cur]) > 0
else 0
)
record["case_precision_" + task_cur] = (
record["pos_true_cnt_" + task_cur]
/ (record["pos_true_cnt_" + task_cur] + record["pos_false_cnt_" + task_cur])
if (record["pos_true_cnt_" + task_cur] + record["pos_false_cnt_" + task_cur]) > 0
else 0
)
record["f1_" + task_cur] = (
2
* record["case_recall_" + task_cur]
* record["case_precision_" + task_cur]
/ (record["case_recall_" + task_cur] + record["case_precision_" + task_cur])
if (record["case_recall_" + task_cur] + record["case_precision_" + task_cur]) > 0
else 0
)
case_res = "case_level:\nprecision: {:.4f}, recall: {:.4f}, f1: {:.4f}".format(
record["case_precision_" + task_cur],
record["case_recall_" + task_cur],
record["f1_" + task_cur],
)
print(case_res)
print(char_res)
return {
"task_type": task_cur,
"span_level": {
"precision": round(record["precision" + task_cur], 4),
"recall": round(record["recall" + task_cur], 4),
"f1": round(record["f1" + task_cur], 4),
"match_size": record["match_size_" + task_cur],
"prediction": record["prediction_" + task_cur],
"ground_truth": record["groud_truth_" + task_cur],
},
"case_level": {
"precision": round(record["case_precision_" + task_cur], 4),
"recall": round(record["case_recall_" + task_cur], 4),
"f1": round(record["f1_" + task_cur], 4),
"pos_true_cnt": record["pos_true_cnt_" + task_cur],
"neg_true_cnt": record["neg_true_cnt_" + task_cur],
"neg_false_cnt": record["neg_false_cnt_" + task_cur],
"pos_false_cnt": record["pos_false_cnt_" + task_cur],
},
}
def evaluate_results(
results: List[Dict[str, Any]],
record: Dict[str, int],
chosen_task: Sequence[str],
filepath: str,
) -> List[Dict[str, Any]]:
chosen = list(chosen_task) + ["All"]
for sample in results:
response = sample["response"]
labels = sample["labels"]
output = sample["output"]
task = sample["task_type"]
res = cal_metrics(response, labels, output)
(
temp_tp,
temp_pred_len,
temp_gold_len,
pos_true_cnt,
neg_true_cnt,
neg_false_cnt,
pos_false_cnt,
) = res
for task_cur in chosen:
if task_cur == task or task_cur == "All":
record["match_size_" + task_cur] += temp_tp
record["prediction_" + task_cur] += temp_pred_len
record["groud_truth_" + task_cur] += temp_gold_len
record["pos_true_cnt_" + task_cur] += pos_true_cnt
record["neg_true_cnt_" + task_cur] += neg_true_cnt
record["neg_false_cnt_" + task_cur] += neg_false_cnt
record["pos_false_cnt_" + task_cur] += pos_false_cnt
all_metrics = []
for task_cur in chosen:
all_metrics.append(print_metrics(task_cur, record))
print("chosen task: {}".format(chosen))
print("filepath: {}".format(filepath))
print("test_data_size: {}".format(len(results)))
return all_metrics
def average_precision_case_detection(results_subset: List[Dict[str, Any]]) -> float:
"""
样本级检测 Average Precision:正类为金标存在幻觉 span(labels 非空),
预测分数与 cal_metrics 的 case 口径一致:``output`` 为非空 list 则为 1,否则 0。
无正样本时返回 0.0。
"""
if not results_subset:
return 0.0
y_true: List[int] = []
y_score: List[float] = []
for s in results_subset:
y_true.append(1 if s.get("labels") else 0)
out = s.get("output")
y_score.append(1.0 if isinstance(out, list) and len(out) > 0 else 0.0)
n_pos = sum(y_true)
if n_pos == 0:
return 0.0
order = sorted(range(len(y_true)), key=lambda i: (-y_score[i], -i))
tp = 0
ap = 0.0
for rank, idx in enumerate(order, start=1):
if y_true[idx] == 1:
tp += 1
ap += tp / rank
return ap / n_pos
def evaluate_results_by_group_key(
results: List[Dict[str, Any]],
filepath: str,
group_key: str = "lang",
) -> List[Dict[str, Any]]:
"""
按样本字段 group_key(如 PsiloQA 的 lang)分组累计 span/case 指标,并写入
case_level.average_precision;最后为汇总桶 All。
返回 dict 中以 group_key 为顶层字段名(如 lang),替代原 task_type。
"""
def get_group(sample: Dict[str, Any]) -> str:
v = sample.get(group_key)
if v is None or v == "":
return "unknown"
return str(v)
groups = sorted({get_group(s) for s in results})
ordered = groups + ["All"]
records: Dict[str, Dict[str, Any]] = {b: collections.defaultdict(int) for b in ordered}
samples_per: Dict[str, List[Dict[str, Any]]] = {b: [] for b in groups}
samples_per["All"] = []
for sample in results:
samples_per[get_group(sample)].append(sample)
samples_per["All"].append(sample)
response = sample["response"]
labels = sample["labels"]
output = sample["output"]
res = cal_metrics(response, labels, output)
(
temp_tp,
temp_pred_len,
temp_gold_len,
pos_true_cnt,
neg_true_cnt,
neg_false_cnt,
pos_false_cnt,
) = res
for b in (get_group(sample), "All"):
task_cur = b
rec = records[b]
rec["match_size_" + task_cur] += temp_tp
rec["prediction_" + task_cur] += temp_pred_len
rec["groud_truth_" + task_cur] += temp_gold_len
rec["pos_true_cnt_" + task_cur] += pos_true_cnt
rec["neg_true_cnt_" + task_cur] += neg_true_cnt
rec["neg_false_cnt_" + task_cur] += neg_false_cnt
rec["pos_false_cnt_" + task_cur] += pos_false_cnt
all_metrics: List[Dict[str, Any]] = []
for b in ordered:
m = print_metrics(b, records[b])
m[group_key] = m.pop("task_type")
ap = average_precision_case_detection(samples_per[b])
m["case_level"]["average_precision"] = round(ap, 4)
print(" average_precision (case-level, nonempty output list = 1): {:.4f}".format(ap))
all_metrics.append(m)
print("group_by {}: {}".format(group_key, ordered))
print("filepath: {}".format(filepath))
print("test_data_size: {}".format(len(results)))
return all_metrics
def parse_output(output_str: str) -> List[str]:
output = re.findall(r"""{"hallucination list": \[.*?\]}""", output_str)
if not len(output):
return []
output = output[-1]
output = json_repair.loads(output)
if "hallucination list" in output:
return output["hallucination list"]
if isinstance(output, list):
return output
print("ERROR: hallucination list not found in output")
return []
def trans_instruction(ins_ori: str, task_word: str) -> str:
if "Your task" not in ins_ori:
print("error")
ins_ori = ins_ori.rsplit("Your task", 1)[0]
ins = ins_ori.strip() + "\n" + extra_sft_prompt.replace("<|task_word|>", task_word)
return ins
def trans_instruction_reasoning(ins_ori: str, task_word: str) -> str:
if "Your task" not in ins_ori:
print("error")
ins_ori = ins_ori.rsplit("Your task", 1)[0]
ins = (
ins_ori.strip()
+ "\n"
+ extra_sft_prompt_reasoning.replace("<|task_word|>", task_word)
)
return ins
def labels_have_any_supervision(results: List[Dict[str, Any]]) -> bool:
for s in results:
if s.get("labels"):
return True
return False
|