"""Verifiable rewards. Math: last \\boxed{} answer checked with math-verify against the gold. HotpotQA: exact match after official normalization (EM/F1 as in skill_dynamics.scoring). ProverQA: the option letter (A True / B False / C Uncertain) on the final-answer line equals the gold.""" import re import string import threading from collections import Counter from .prompts import DOMAIN_OF_SOURCE from .segment import FINAL_PREFIX PROVER_WORDS = {"true": "A", "false": "B", "uncertain": "C", "unknown": "C"} def last_boxed(text): """Content of the last \\boxed{...} (or \\fbox{...}) with balanced braces, else None.""" idx = max(text.rfind("\\boxed"), text.rfind("\\fbox")) if idx < 0: return None i = text.find("{", idx) if i < 0: rest = text[idx:].split("$")[0].split() return rest[1] if len(rest) > 1 else None depth, j = 0, i while j < len(text): if text[j] == "{": depth += 1 elif text[j] == "}": depth -= 1 if depth == 0: return text[i + 1:j] j += 1 return None FINAL_LINE_RE = re.compile(r"(?im)" + FINAL_PREFIX + r"(.*)$") def final_answer_line(text): """Text after the last "Final answer:" opener (same prefix as the segmenter's terminal segment); when nothing follows it on that line, the next non-empty line.""" matches = list(FINAL_LINE_RE.finditer(text)) if not matches: return "" answer = matches[-1].group(1).strip().strip("*_").strip() if not answer: rest = [line for line in text[matches[-1].end():].splitlines() if line.strip()] answer = rest[0].strip().strip("*_").strip() if rest else "" return answer def math_gold_from_solution(solution): return last_boxed(solution) def gsm8k_gold(answer_field): return answer_field.split("####")[-1].strip().replace(",", "") def extract_math_answer(response): boxed = last_boxed(response) if boxed is not None: return boxed line = final_answer_line(response) return line.strip("$ .") if line else None def verify_math(response, gold): import inspect from math_verify import parse, verify pred = extract_math_answer(response) if pred is None or not str(gold).strip(): return 0.0 main = threading.current_thread() is threading.main_thread() timeout = 5 if main else None # Timeout arguments exist only in newer math-verify releases; older ones time out internally. p_kw = {"parsing_timeout": timeout} if "parsing_timeout" in inspect.signature(parse).parameters else {} v_kw = {"timeout_seconds": timeout} if "timeout_seconds" in inspect.signature(verify).parameters else {} try: gold_parsed = parse("$" + str(gold) + "$", **p_kw) pred_parsed = parse("$" + pred + "$", **p_kw) if not gold_parsed or not pred_parsed: return float(_strip(pred) == _strip(str(gold))) return float(verify(gold_parsed, pred_parsed, **v_kw)) except Exception: return float(_strip(pred) == _strip(str(gold))) def _strip(s): return re.sub(r"\s+", "", s).rstrip(".").replace("\\!", "").replace("dfrac", "frac").replace("tfrac", "frac") def normalize_answer(text): text = "".join(c for c in text.lower() if c not in string.punctuation) return " ".join(re.sub(r"\b(a|an|the)\b", " ", text).split()) def hotpot_scores(predicted, expected): pred, gold = normalize_answer(predicted), normalize_answer(expected) em = float(pred == gold) if (pred in {"yes", "no", "noanswer"} or gold in {"yes", "no", "noanswer"}) and pred != gold: return {"em": em, "f1": 0.0} overlap = sum((Counter(pred.split()) & Counter(gold.split())).values()) f1 = 2 * overlap / (len(pred.split()) + len(gold.split())) if overlap else 0.0 return {"em": em, "f1": f1} def option_letter(answer): """ProverQA option (A/B/C) from a final-answer line: 'B', 'B) False', '\\boxed{B}', 'Option B' or 'False'.""" a = re.sub(r"\\boxed\{([^}]*)\}|\$|\*\*", r"\1", answer).strip() m = re.match(r"\(?\s*([ABC])\s*(?:\)|\.|:|,|$|\s)", a) or re.search(r"\b[Oo]ption\s*\(?([ABC])\b|\(([ABC])\)", a) if m: return next(g for g in m.groups() if g) words = {PROVER_WORDS[w] for w in re.findall(r"\b(true|false|uncertain|unknown)\b", a.lower())} return words.pop() if len(words) == 1 else None def verify(data_source, response, gold): """Binary verified reward R in {0, 1} plus diagnostics.""" domain = DOMAIN_OF_SOURCE[data_source] if domain == "math": r = verify_math(response, gold) return {"score": r, "acc": r, "has_answer": float(extract_math_answer(response) is not None)} if domain == "proverqa": letter = option_letter(final_answer_line(response)) r = float(letter == str(gold).strip().upper()) return {"score": r, "acc": r, "has_answer": float(letter is not None)} answer = final_answer_line(response) s = hotpot_scores(answer, gold) return {"score": s["em"], "acc": s["em"], "f1": s["f1"], "has_answer": float(bool(answer))}