Model: Xirui1208/selective-readtwice-7b-early-evaluated-20260928 Source: Original Platform
349 lines
12 KiB
Python
349 lines
12 KiB
Python
"""Shared strict final-answer parsing and source-aware scoring contracts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections import Counter
|
|
from collections.abc import Iterable
|
|
import re
|
|
import string
|
|
from typing import Any
|
|
|
|
|
|
OPENQA_SUBEM = "openqa_subem"
|
|
NORMALIZED_EXACT = "normalized_exact"
|
|
MCQ_EXACT = "mcq_exact"
|
|
SUMMARY_F1_030 = "summary_f1_030"
|
|
RULER_ALL_ITEMS = "ruler_all_items"
|
|
UNORDERED_LIST_EXACT = "unordered_list_exact"
|
|
|
|
ANSWER_STYLES = frozenset(
|
|
{
|
|
OPENQA_SUBEM,
|
|
NORMALIZED_EXACT,
|
|
MCQ_EXACT,
|
|
SUMMARY_F1_030,
|
|
RULER_ALL_ITEMS,
|
|
UNORDERED_LIST_EXACT,
|
|
}
|
|
)
|
|
SOURCE_STYLE_ALLOWLIST = {
|
|
"2wikimultihopqa": frozenset({OPENQA_SUBEM}),
|
|
"babilong": frozenset({NORMALIZED_EXACT, UNORDERED_LIST_EXACT}),
|
|
"hotpotqa": frozenset({OPENQA_SUBEM}),
|
|
"longbench_upstream": frozenset({OPENQA_SUBEM}),
|
|
"musique": frozenset({OPENQA_SUBEM}),
|
|
"narrativeqa_like": frozenset({OPENQA_SUBEM}),
|
|
"qmsum": frozenset({SUMMARY_F1_030}),
|
|
"ruler_niah": frozenset({RULER_ALL_ITEMS}),
|
|
"ruler_vt_aggregation": frozenset({RULER_ALL_ITEMS}),
|
|
"squad_like": frozenset({OPENQA_SUBEM}),
|
|
"squad_mcq_hard": frozenset({MCQ_EXACT}),
|
|
"strict_mcq": frozenset({MCQ_EXACT}),
|
|
}
|
|
SUMMARY_F1_THRESHOLD = 0.30
|
|
|
|
_RESULT_KEYS = (
|
|
"score",
|
|
"acc",
|
|
"sub_em",
|
|
"em",
|
|
"answer_quality",
|
|
"answer_f1",
|
|
"item_coverage",
|
|
"set_f1",
|
|
"answer_box_valid",
|
|
)
|
|
|
|
|
|
def extract_last_boxed(text: Any) -> str | None:
|
|
"""Return the final complete, nonempty, case-sensitive boxed answer."""
|
|
|
|
value = str(text)
|
|
command = r"\boxed"
|
|
marker = r"\boxed{"
|
|
command_start = value.rfind(command)
|
|
if command_start < 0 or not value.startswith(marker, command_start):
|
|
return None
|
|
start = command_start
|
|
cursor = start + len(marker)
|
|
content_start = cursor
|
|
depth = 1
|
|
while cursor < len(value):
|
|
character = value[cursor]
|
|
backslashes = 0
|
|
previous = cursor - 1
|
|
while previous >= 0 and value[previous] == "\\":
|
|
backslashes += 1
|
|
previous -= 1
|
|
escaped = bool(backslashes % 2)
|
|
if character == "{" and not escaped:
|
|
depth += 1
|
|
elif character == "}" and not escaped:
|
|
depth -= 1
|
|
if depth == 0:
|
|
answer = value[content_start:cursor].strip()
|
|
return answer or None
|
|
if depth < 0:
|
|
return None
|
|
cursor += 1
|
|
return None
|
|
|
|
|
|
def normalize_answer(text: Any) -> str:
|
|
value = str(text or "").lower()
|
|
value = "".join(character for character in value if character not in string.punctuation)
|
|
value = re.sub(r"\b(a|an|the)\b", " ", value)
|
|
return " ".join(value.split())
|
|
|
|
|
|
def _token_f1(normalized_prediction: str, normalized_gold: str) -> float:
|
|
if not normalized_prediction or not normalized_gold:
|
|
return 0.0
|
|
prediction_tokens = normalized_prediction.split()
|
|
gold_tokens = normalized_gold.split()
|
|
overlap = sum((Counter(prediction_tokens) & Counter(gold_tokens)).values())
|
|
if overlap == 0:
|
|
return 0.0
|
|
precision = overlap / len(prediction_tokens)
|
|
recall = overlap / len(gold_tokens)
|
|
return 2.0 * precision * recall / (precision + recall)
|
|
|
|
|
|
def formal_qa_metrics(prediction: Any, gold: Any) -> dict[str, float]:
|
|
"""Return normalized SubEM/EM/F1, including normalized-empty zeroing."""
|
|
|
|
normalized_prediction = normalize_answer(prediction)
|
|
normalized_gold = normalize_answer(gold)
|
|
if not normalized_prediction or not normalized_gold:
|
|
return {"sub_em": 0.0, "em": 0.0, "f1": 0.0}
|
|
exact = float(normalized_prediction == normalized_gold)
|
|
special = {"yes", "no", "noanswer"}
|
|
if (
|
|
normalized_prediction in special or normalized_gold in special
|
|
) and normalized_prediction != normalized_gold:
|
|
substring = 0.0
|
|
f1 = 0.0
|
|
else:
|
|
substring = float(
|
|
normalized_gold in normalized_prediction
|
|
or normalized_prediction in normalized_gold
|
|
)
|
|
f1 = _token_f1(normalized_prediction, normalized_gold)
|
|
return {"sub_em": substring, "em": exact, "f1": f1}
|
|
|
|
|
|
def _aliases(ground_truth: Any) -> tuple[str, ...]:
|
|
if isinstance(ground_truth, (str, bytes)) or ground_truth is None:
|
|
raise ValueError("ground_truth must be a non-empty answer-alias sequence")
|
|
if hasattr(ground_truth, "tolist"):
|
|
ground_truth = ground_truth.tolist()
|
|
if not isinstance(ground_truth, Iterable):
|
|
raise ValueError("ground_truth must be a non-empty answer-alias sequence")
|
|
aliases = tuple(str(value).strip() for value in ground_truth)
|
|
if not aliases or any(not value for value in aliases):
|
|
raise ValueError("ground_truth aliases must all be nonempty")
|
|
return aliases
|
|
|
|
|
|
def _comma_items(value: str, *, ground_truth: bool) -> tuple[str, ...] | None:
|
|
items = tuple(item.strip() for item in str(value).split(","))
|
|
if not items or any(not item for item in items):
|
|
if ground_truth:
|
|
raise ValueError("comma-separated ground_truth contains an empty item")
|
|
return None
|
|
return items
|
|
|
|
|
|
def _zero_result() -> dict[str, float]:
|
|
return {name: 0.0 for name in _RESULT_KEYS}
|
|
|
|
|
|
def _result(
|
|
*,
|
|
correct: float,
|
|
sub_em: float,
|
|
em: float,
|
|
answer_quality: float,
|
|
answer_f1: float = 0.0,
|
|
item_coverage: float = 0.0,
|
|
set_f1: float = 0.0,
|
|
) -> dict[str, float]:
|
|
if correct not in {0.0, 1.0}:
|
|
raise ValueError(f"correctness must be binary, got {correct!r}")
|
|
values = {
|
|
"score": correct,
|
|
"acc": correct,
|
|
"sub_em": float(sub_em),
|
|
"em": float(em),
|
|
"answer_quality": float(answer_quality),
|
|
"answer_f1": float(answer_f1),
|
|
"item_coverage": float(item_coverage),
|
|
"set_f1": float(set_f1),
|
|
"answer_box_valid": 1.0,
|
|
}
|
|
for name, value in values.items():
|
|
if value < 0.0 or value > 1.0:
|
|
raise ValueError(f"{name} must be in [0, 1], got {value!r}")
|
|
return values
|
|
|
|
|
|
def _set_f1(prediction: frozenset[str], gold: frozenset[str]) -> float:
|
|
if not prediction or not gold:
|
|
return 0.0
|
|
overlap = len(prediction & gold)
|
|
if overlap == 0:
|
|
return 0.0
|
|
precision = overlap / len(prediction)
|
|
recall = overlap / len(gold)
|
|
return 2.0 * precision * recall / (precision + recall)
|
|
|
|
|
|
def score_boxed_answer(
|
|
solution: Any,
|
|
ground_truth: Any,
|
|
reward_style: Any,
|
|
*,
|
|
source_suffix: str,
|
|
) -> dict[str, float]:
|
|
"""Score one final response under an exact source-by-style contract."""
|
|
|
|
if not isinstance(reward_style, str) or reward_style not in ANSWER_STYLES:
|
|
raise ValueError(f"unknown reward_model.style: {reward_style!r}")
|
|
allowed = SOURCE_STYLE_ALLOWLIST.get(str(source_suffix))
|
|
if allowed is None or reward_style not in allowed:
|
|
raise ValueError(
|
|
"reward_model.style is not allowed for source: "
|
|
f"source={source_suffix!r}, style={reward_style!r}"
|
|
)
|
|
aliases = _aliases(ground_truth)
|
|
prediction = extract_last_boxed(solution)
|
|
if prediction is None:
|
|
return _zero_result()
|
|
|
|
if reward_style in {OPENQA_SUBEM, NORMALIZED_EXACT, SUMMARY_F1_030}:
|
|
metrics = [formal_qa_metrics(prediction, alias) for alias in aliases]
|
|
answer_f1 = max(metric["f1"] for metric in metrics)
|
|
exact = max(metric["em"] for metric in metrics)
|
|
sub_em = max(metric["sub_em"] for metric in metrics)
|
|
if reward_style == OPENQA_SUBEM:
|
|
correct = sub_em
|
|
elif reward_style == NORMALIZED_EXACT:
|
|
correct = exact
|
|
sub_em = exact
|
|
else:
|
|
correct = float(answer_f1 >= SUMMARY_F1_THRESHOLD)
|
|
return _result(
|
|
correct=correct,
|
|
sub_em=sub_em,
|
|
em=exact,
|
|
answer_quality=answer_f1,
|
|
answer_f1=answer_f1,
|
|
)
|
|
|
|
if reward_style == MCQ_EXACT:
|
|
normalized_aliases = tuple(alias.upper() for alias in aliases)
|
|
if any(
|
|
len(alias) != 1 or alias not in "ABCD"
|
|
for alias in normalized_aliases
|
|
):
|
|
raise ValueError("mcq_exact ground_truth must contain only A-D labels")
|
|
normalized_prediction = prediction.upper()
|
|
correct = float(
|
|
len(normalized_prediction) == 1
|
|
and normalized_prediction in normalized_aliases
|
|
)
|
|
return _result(
|
|
correct=correct,
|
|
sub_em=correct,
|
|
em=correct,
|
|
answer_quality=correct,
|
|
answer_f1=correct,
|
|
)
|
|
|
|
if reward_style == RULER_ALL_ITEMS:
|
|
prediction_folded = prediction.casefold()
|
|
coverages = []
|
|
for alias in aliases:
|
|
references = _comma_items(alias, ground_truth=True)
|
|
assert references is not None
|
|
folded_references = tuple(reference.casefold() for reference in references)
|
|
if any(not reference for reference in folded_references):
|
|
raise ValueError("ruler_all_items ground_truth contains an empty item")
|
|
if len(set(folded_references)) != len(folded_references):
|
|
raise ValueError(
|
|
"ruler_all_items ground_truth contains duplicate casefolded items"
|
|
)
|
|
coverage = sum(
|
|
float(reference in prediction_folded)
|
|
for reference in folded_references
|
|
) / len(folded_references)
|
|
coverages.append(coverage)
|
|
item_coverage = max(coverages)
|
|
correct = float(item_coverage == 1.0)
|
|
return _result(
|
|
correct=correct,
|
|
sub_em=correct,
|
|
em=correct,
|
|
answer_quality=item_coverage,
|
|
item_coverage=item_coverage,
|
|
)
|
|
|
|
if reward_style == UNORDERED_LIST_EXACT:
|
|
raw_prediction_items = _comma_items(prediction, ground_truth=False)
|
|
if raw_prediction_items is None:
|
|
return _result(
|
|
correct=0.0,
|
|
sub_em=0.0,
|
|
em=0.0,
|
|
answer_quality=0.0,
|
|
)
|
|
prediction_items = frozenset(
|
|
normalize_answer(item) for item in raw_prediction_items
|
|
)
|
|
if not prediction_items or any(not item for item in prediction_items):
|
|
return _result(
|
|
correct=0.0,
|
|
sub_em=0.0,
|
|
em=0.0,
|
|
answer_quality=0.0,
|
|
)
|
|
candidate_scores = []
|
|
for alias in aliases:
|
|
raw_gold_items = _comma_items(alias, ground_truth=True)
|
|
assert raw_gold_items is not None
|
|
gold_items = frozenset(normalize_answer(item) for item in raw_gold_items)
|
|
if not gold_items or any(not item for item in gold_items):
|
|
raise ValueError(
|
|
"unordered_list_exact ground_truth normalizes to an empty item"
|
|
)
|
|
quality = _set_f1(prediction_items, gold_items)
|
|
candidate_scores.append((float(prediction_items == gold_items), quality))
|
|
correct = max(value[0] for value in candidate_scores)
|
|
set_f1 = max(value[1] for value in candidate_scores)
|
|
return _result(
|
|
correct=correct,
|
|
sub_em=correct,
|
|
em=correct,
|
|
answer_quality=set_f1,
|
|
set_f1=set_f1,
|
|
)
|
|
|
|
raise AssertionError(f"unhandled reward style: {reward_style}")
|
|
|
|
|
|
__all__ = [
|
|
"ANSWER_STYLES",
|
|
"MCQ_EXACT",
|
|
"NORMALIZED_EXACT",
|
|
"OPENQA_SUBEM",
|
|
"RULER_ALL_ITEMS",
|
|
"SOURCE_STYLE_ALLOWLIST",
|
|
"SUMMARY_F1_030",
|
|
"SUMMARY_F1_THRESHOLD",
|
|
"UNORDERED_LIST_EXACT",
|
|
"extract_last_boxed",
|
|
"formal_qa_metrics",
|
|
"normalize_answer",
|
|
"score_boxed_answer",
|
|
]
|