diff --git a/tasks/0000_526_526258_qa_2/tests/grader.py b/tasks/0000_526_526258_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0000_526_526258_qa_2/tests/grader.py +++ b/tasks/0000_526_526258_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0000_767_767688_qa_4/tests/grader.py b/tasks/0000_767_767688_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0000_767_767688_qa_4/tests/grader.py +++ b/tasks/0000_767_767688_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0000_780_780974_qa_4/tests/grader.py b/tasks/0000_780_780974_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0000_780_780974_qa_4/tests/grader.py +++ b/tasks/0000_780_780974_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_133_1133625_qa_4/tests/grader.py b/tasks/0001_133_1133625_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_133_1133625_qa_4/tests/grader.py +++ b/tasks/0001_133_1133625_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_160_1160639_qa_1/tests/grader.py b/tasks/0001_160_1160639_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_160_1160639_qa_1/tests/grader.py +++ b/tasks/0001_160_1160639_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_188_1188925_qa_3/tests/grader.py b/tasks/0001_188_1188925_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_188_1188925_qa_3/tests/grader.py +++ b/tasks/0001_188_1188925_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_189_1189227_qa_2/tests/grader.py b/tasks/0001_189_1189227_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_189_1189227_qa_2/tests/grader.py +++ b/tasks/0001_189_1189227_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_189_1189227_qa_5/tests/grader.py b/tasks/0001_189_1189227_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_189_1189227_qa_5/tests/grader.py +++ b/tasks/0001_189_1189227_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_191_1191057_qa_4/tests/grader.py b/tasks/0001_191_1191057_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_191_1191057_qa_4/tests/grader.py +++ b/tasks/0001_191_1191057_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_196_1196803_qa_3/tests/grader.py b/tasks/0001_196_1196803_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_196_1196803_qa_3/tests/grader.py +++ b/tasks/0001_196_1196803_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_239_1239559_qa_4/tests/grader.py b/tasks/0001_239_1239559_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_239_1239559_qa_4/tests/grader.py +++ b/tasks/0001_239_1239559_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_243_1243037_qa_2/tests/grader.py b/tasks/0001_243_1243037_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_243_1243037_qa_2/tests/grader.py +++ b/tasks/0001_243_1243037_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_349_1349978_qa_4/tests/grader.py b/tasks/0001_349_1349978_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_349_1349978_qa_4/tests/grader.py +++ b/tasks/0001_349_1349978_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_522_1522371_qa_2/tests/grader.py b/tasks/0001_522_1522371_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_522_1522371_qa_2/tests/grader.py +++ b/tasks/0001_522_1522371_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_527_1527039_qa_3/tests/grader.py b/tasks/0001_527_1527039_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_527_1527039_qa_3/tests/grader.py +++ b/tasks/0001_527_1527039_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_538_1538781_qa_4/tests/grader.py b/tasks/0001_538_1538781_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_538_1538781_qa_4/tests/grader.py +++ b/tasks/0001_538_1538781_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_541_1541002_qa_4/tests/grader.py b/tasks/0001_541_1541002_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_541_1541002_qa_4/tests/grader.py +++ b/tasks/0001_541_1541002_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_583_1583897_qa_3/tests/grader.py b/tasks/0001_583_1583897_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_583_1583897_qa_3/tests/grader.py +++ b/tasks/0001_583_1583897_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_623_1623388_qa_1/tests/grader.py b/tasks/0001_623_1623388_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_623_1623388_qa_1/tests/grader.py +++ b/tasks/0001_623_1623388_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_637_1637985_qa_3/tests/grader.py b/tasks/0001_637_1637985_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_637_1637985_qa_3/tests/grader.py +++ b/tasks/0001_637_1637985_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_646_1646297_qa_2/tests/grader.py b/tasks/0001_646_1646297_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_646_1646297_qa_2/tests/grader.py +++ b/tasks/0001_646_1646297_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_690_1690621_qa_2/tests/grader.py b/tasks/0001_690_1690621_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_690_1690621_qa_2/tests/grader.py +++ b/tasks/0001_690_1690621_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_885_1885477_qa_5/tests/grader.py b/tasks/0001_885_1885477_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_885_1885477_qa_5/tests/grader.py +++ b/tasks/0001_885_1885477_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_990_1990392_qa_4/tests/grader.py b/tasks/0001_990_1990392_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_990_1990392_qa_4/tests/grader.py +++ b/tasks/0001_990_1990392_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0002_264_2264461_qa_1/tests/grader.py b/tasks/0002_264_2264461_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_264_2264461_qa_1/tests/grader.py +++ b/tasks/0002_264_2264461_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0010_708_10708335_qa_2/tests/grader.py b/tasks/0010_708_10708335_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0010_708_10708335_qa_2/tests/grader.py +++ b/tasks/0010_708_10708335_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0011_587_11587305_qa_5/tests/grader.py b/tasks/0011_587_11587305_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0011_587_11587305_qa_5/tests/grader.py +++ b/tasks/0011_587_11587305_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0012_112_12112975_qa_3/tests/grader.py b/tasks/0012_112_12112975_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0012_112_12112975_qa_3/tests/grader.py +++ b/tasks/0012_112_12112975_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0012_161_12161282_qa_4/tests/grader.py b/tasks/0012_161_12161282_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0012_161_12161282_qa_4/tests/grader.py +++ b/tasks/0012_161_12161282_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0012_941_12941575_qa_2/tests/grader.py b/tasks/0012_941_12941575_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0012_941_12941575_qa_2/tests/grader.py +++ b/tasks/0012_941_12941575_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0013_169_13169934_qa_5/tests/grader.py b/tasks/0013_169_13169934_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_169_13169934_qa_5/tests/grader.py +++ b/tasks/0013_169_13169934_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0013_839_13839617_qa_5/tests/grader.py b/tasks/0013_839_13839617_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_839_13839617_qa_5/tests/grader.py +++ b/tasks/0013_839_13839617_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0014_701_14701455_qa_3/tests/grader.py b/tasks/0014_701_14701455_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0014_701_14701455_qa_3/tests/grader.py +++ b/tasks/0014_701_14701455_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0016_135_16135360_qa_2/tests/grader.py b/tasks/0016_135_16135360_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0016_135_16135360_qa_2/tests/grader.py +++ b/tasks/0016_135_16135360_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0016_558_16558367_qa_1/environment/Dockerfile b/tasks/0016_558_16558367_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0016_558_16558367_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0016_558_16558367_qa_1/environment/pull_bucket.py b/tasks/0016_558_16558367_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0016_558_16558367_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0016_558_16558367_qa_1/tests/grader.py b/tasks/0016_558_16558367_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0016_558_16558367_qa_1/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0016_558_16558367_qa_1/tests/test.sh b/tasks/0016_558_16558367_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0016_558_16558367_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0016_712_16712977_qa_5/tests/grader.py b/tasks/0016_712_16712977_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0016_712_16712977_qa_5/tests/grader.py +++ b/tasks/0016_712_16712977_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0017_247_17247673_qa_2/tests/grader.py b/tasks/0017_247_17247673_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0017_247_17247673_qa_2/tests/grader.py +++ b/tasks/0017_247_17247673_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0017_311_17311492_qa_2/tests/grader.py b/tasks/0017_311_17311492_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0017_311_17311492_qa_2/tests/grader.py +++ b/tasks/0017_311_17311492_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0017_565_17565404_qa_2/tests/grader.py b/tasks/0017_565_17565404_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0017_565_17565404_qa_2/tests/grader.py +++ b/tasks/0017_565_17565404_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0018_038_18038519_qa_5/tests/grader.py b/tasks/0018_038_18038519_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0018_038_18038519_qa_5/tests/grader.py +++ b/tasks/0018_038_18038519_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0019_570_19570997_qa_1/tests/grader.py b/tasks/0019_570_19570997_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0019_570_19570997_qa_1/tests/grader.py +++ b/tasks/0019_570_19570997_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0021_030_21030697_qa_5/environment/Dockerfile b/tasks/0021_030_21030697_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_030_21030697_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_030_21030697_qa_5/environment/pull_bucket.py b/tasks/0021_030_21030697_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_030_21030697_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0021_030_21030697_qa_5/tests/grader.py b/tasks/0021_030_21030697_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0021_030_21030697_qa_5/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0021_030_21030697_qa_5/tests/test.sh b/tasks/0021_030_21030697_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_030_21030697_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0021_353_21353656_qa_1/tests/grader.py b/tasks/0021_353_21353656_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_353_21353656_qa_1/tests/grader.py +++ b/tasks/0021_353_21353656_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0021_643_21643452_qa_5/environment/Dockerfile b/tasks/0021_643_21643452_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0021_643_21643452_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0021_643_21643452_qa_5/environment/pull_bucket.py b/tasks/0021_643_21643452_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0021_643_21643452_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0021_643_21643452_qa_5/tests/grader.py b/tasks/0021_643_21643452_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0021_643_21643452_qa_5/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0021_643_21643452_qa_5/tests/test.sh b/tasks/0021_643_21643452_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0021_643_21643452_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0021_901_21901400_qa_3/tests/grader.py b/tasks/0021_901_21901400_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_901_21901400_qa_3/tests/grader.py +++ b/tasks/0021_901_21901400_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0022_886_22886038_qa_4/tests/grader.py b/tasks/0022_886_22886038_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0022_886_22886038_qa_4/tests/grader.py +++ b/tasks/0022_886_22886038_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0023_468_23468316_qa_2/tests/grader.py b/tasks/0023_468_23468316_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_468_23468316_qa_2/tests/grader.py +++ b/tasks/0023_468_23468316_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0023_721_23721684_qa_4/tests/grader.py b/tasks/0023_721_23721684_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_721_23721684_qa_4/tests/grader.py +++ b/tasks/0023_721_23721684_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0023_846_23846255_qa_1/environment/Dockerfile b/tasks/0023_846_23846255_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0023_846_23846255_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0023_846_23846255_qa_1/environment/pull_bucket.py b/tasks/0023_846_23846255_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0023_846_23846255_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0023_846_23846255_qa_1/tests/grader.py b/tasks/0023_846_23846255_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0023_846_23846255_qa_1/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0023_846_23846255_qa_1/tests/test.sh b/tasks/0023_846_23846255_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0023_846_23846255_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0024_081_24081260_qa_3/tests/grader.py b/tasks/0024_081_24081260_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_081_24081260_qa_3/tests/grader.py +++ b/tasks/0024_081_24081260_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0024_796_24796579_qa_1/tests/grader.py b/tasks/0024_796_24796579_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_796_24796579_qa_1/tests/grader.py +++ b/tasks/0024_796_24796579_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0024_991_24991983_qa_2/environment/Dockerfile b/tasks/0024_991_24991983_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0024_991_24991983_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0024_991_24991983_qa_2/environment/pull_bucket.py b/tasks/0024_991_24991983_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0024_991_24991983_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0024_991_24991983_qa_2/tests/grader.py b/tasks/0024_991_24991983_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0024_991_24991983_qa_2/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0024_991_24991983_qa_2/tests/test.sh b/tasks/0024_991_24991983_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0024_991_24991983_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0026_895_26895005_qa_1/tests/grader.py b/tasks/0026_895_26895005_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0026_895_26895005_qa_1/tests/grader.py +++ b/tasks/0026_895_26895005_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0029_108_29108182_qa_1/tests/grader.py b/tasks/0029_108_29108182_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0029_108_29108182_qa_1/tests/grader.py +++ b/tasks/0029_108_29108182_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0029_784_29784165_qa_1/tests/grader.py b/tasks/0029_784_29784165_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0029_784_29784165_qa_1/tests/grader.py +++ b/tasks/0029_784_29784165_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0030_348_30348412_qa_2/tests/grader.py b/tasks/0030_348_30348412_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_348_30348412_qa_2/tests/grader.py +++ b/tasks/0030_348_30348412_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0030_804_30804903_qa_1/tests/grader.py b/tasks/0030_804_30804903_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_804_30804903_qa_1/tests/grader.py +++ b/tasks/0030_804_30804903_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0030_817_30817038_qa_2/tests/grader.py b/tasks/0030_817_30817038_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_817_30817038_qa_2/tests/grader.py +++ b/tasks/0030_817_30817038_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0031_987_31987709_qa_1/tests/grader.py b/tasks/0031_987_31987709_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_987_31987709_qa_1/tests/grader.py +++ b/tasks/0031_987_31987709_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_101_32101676_qa_2/tests/grader.py b/tasks/0032_101_32101676_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_101_32101676_qa_2/tests/grader.py +++ b/tasks/0032_101_32101676_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_314_32314190_qa_3/tests/grader.py b/tasks/0032_314_32314190_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_314_32314190_qa_3/tests/grader.py +++ b/tasks/0032_314_32314190_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_314_32314190_qa_4/tests/grader.py b/tasks/0032_314_32314190_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_314_32314190_qa_4/tests/grader.py +++ b/tasks/0032_314_32314190_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_386_32386426_qa_3/tests/grader.py b/tasks/0032_386_32386426_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_386_32386426_qa_3/tests/grader.py +++ b/tasks/0032_386_32386426_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_488_32488845_qa_3/tests/grader.py b/tasks/0032_488_32488845_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_488_32488845_qa_3/tests/grader.py +++ b/tasks/0032_488_32488845_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_867_32867580_qa_1/tests/grader.py b/tasks/0032_867_32867580_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_867_32867580_qa_1/tests/grader.py +++ b/tasks/0032_867_32867580_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_057_33057679_qa_1/tests/grader.py b/tasks/0033_057_33057679_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_057_33057679_qa_1/tests/grader.py +++ b/tasks/0033_057_33057679_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_423_33423582_qa_4/tests/grader.py b/tasks/0033_423_33423582_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_423_33423582_qa_4/tests/grader.py +++ b/tasks/0033_423_33423582_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_684_33684962_qa_2/tests/grader.py b/tasks/0033_684_33684962_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_684_33684962_qa_2/tests/grader.py +++ b/tasks/0033_684_33684962_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_684_33684962_qa_5/tests/grader.py b/tasks/0033_684_33684962_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_684_33684962_qa_5/tests/grader.py +++ b/tasks/0033_684_33684962_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_697_33697266_qa_2/tests/grader.py b/tasks/0033_697_33697266_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_697_33697266_qa_2/tests/grader.py +++ b/tasks/0033_697_33697266_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_963_33963401_qa_1/tests/grader.py b/tasks/0033_963_33963401_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_963_33963401_qa_1/tests/grader.py +++ b/tasks/0033_963_33963401_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0034_170_34170800_qa_2/tests/grader.py b/tasks/0034_170_34170800_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_170_34170800_qa_2/tests/grader.py +++ b/tasks/0034_170_34170800_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0034_339_34339717_qa_3/tests/grader.py b/tasks/0034_339_34339717_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_339_34339717_qa_3/tests/grader.py +++ b/tasks/0034_339_34339717_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0034_380_34380054_qa_2/tests/grader.py b/tasks/0034_380_34380054_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0034_380_34380054_qa_2/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0034_912_34912092_qa_5/tests/grader.py b/tasks/0034_912_34912092_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_912_34912092_qa_5/tests/grader.py +++ b/tasks/0034_912_34912092_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0035_121_35121535_qa_1/tests/grader.py b/tasks/0035_121_35121535_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_121_35121535_qa_1/tests/grader.py +++ b/tasks/0035_121_35121535_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0035_745_35745803_qa_1/tests/grader.py b/tasks/0035_745_35745803_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_745_35745803_qa_1/tests/grader.py +++ b/tasks/0035_745_35745803_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0036_436_36436182_qa_5/tests/grader.py b/tasks/0036_436_36436182_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_436_36436182_qa_5/tests/grader.py +++ b/tasks/0036_436_36436182_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0036_916_36916974_qa_1/tests/grader.py b/tasks/0036_916_36916974_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_916_36916974_qa_1/tests/grader.py +++ b/tasks/0036_916_36916974_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0036_927_36927955_qa_1/tests/grader.py b/tasks/0036_927_36927955_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_927_36927955_qa_1/tests/grader.py +++ b/tasks/0036_927_36927955_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_280_38280511_qa_5/tests/grader.py b/tasks/0038_280_38280511_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_280_38280511_qa_5/tests/grader.py +++ b/tasks/0038_280_38280511_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_325_38325022_qa_3/tests/grader.py b/tasks/0038_325_38325022_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_325_38325022_qa_3/tests/grader.py +++ b/tasks/0038_325_38325022_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_547_38547552_qa_3/tests/grader.py b/tasks/0038_547_38547552_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_547_38547552_qa_3/tests/grader.py +++ b/tasks/0038_547_38547552_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_547_38547552_qa_4/tests/grader.py b/tasks/0038_547_38547552_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_547_38547552_qa_4/tests/grader.py +++ b/tasks/0038_547_38547552_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_570_38570610_qa_3/tests/grader.py b/tasks/0038_570_38570610_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_570_38570610_qa_3/tests/grader.py +++ b/tasks/0038_570_38570610_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_688_38688219_qa_1/tests/grader.py b/tasks/0038_688_38688219_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_688_38688219_qa_1/tests/grader.py +++ b/tasks/0038_688_38688219_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_970_38970193_qa_5/tests/grader.py b/tasks/0038_970_38970193_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_970_38970193_qa_5/tests/grader.py +++ b/tasks/0038_970_38970193_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0039_370_39370613_qa_3/tests/grader.py b/tasks/0039_370_39370613_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_370_39370613_qa_3/tests/grader.py +++ b/tasks/0039_370_39370613_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0039_873_39873778_qa_5/tests/grader.py b/tasks/0039_873_39873778_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_873_39873778_qa_5/tests/grader.py +++ b/tasks/0039_873_39873778_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0040_783_40783338_qa_3/tests/grader.py b/tasks/0040_783_40783338_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_783_40783338_qa_3/tests/grader.py +++ b/tasks/0040_783_40783338_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0040_916_40916847_qa_3/tests/grader.py b/tasks/0040_916_40916847_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_916_40916847_qa_3/tests/grader.py +++ b/tasks/0040_916_40916847_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0041_015_41015677_qa_2/tests/grader.py b/tasks/0041_015_41015677_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_015_41015677_qa_2/tests/grader.py +++ b/tasks/0041_015_41015677_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0041_172_41172395_qa_3/tests/grader.py b/tasks/0041_172_41172395_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_172_41172395_qa_3/tests/grader.py +++ b/tasks/0041_172_41172395_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0041_214_41214331_qa_5/tests/grader.py b/tasks/0041_214_41214331_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_214_41214331_qa_5/tests/grader.py +++ b/tasks/0041_214_41214331_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0041_712_41712543_qa_1/tests/grader.py b/tasks/0041_712_41712543_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_712_41712543_qa_1/tests/grader.py +++ b/tasks/0041_712_41712543_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0041_818_41818748_qa_5/environment/Dockerfile b/tasks/0041_818_41818748_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_818_41818748_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_818_41818748_qa_5/environment/pull_bucket.py b/tasks/0041_818_41818748_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_818_41818748_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0041_818_41818748_qa_5/tests/grader.py b/tasks/0041_818_41818748_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0041_818_41818748_qa_5/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0041_818_41818748_qa_5/tests/test.sh b/tasks/0041_818_41818748_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_818_41818748_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0042_773_42773926_qa_3/tests/grader.py b/tasks/0042_773_42773926_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_773_42773926_qa_3/tests/grader.py +++ b/tasks/0042_773_42773926_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0042_991_42991381_qa_5/tests/grader.py b/tasks/0042_991_42991381_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_991_42991381_qa_5/tests/grader.py +++ b/tasks/0042_991_42991381_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0043_069_43069626_qa_4/tests/grader.py b/tasks/0043_069_43069626_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_069_43069626_qa_4/tests/grader.py +++ b/tasks/0043_069_43069626_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0044_193_44193489_qa_1/tests/grader.py b/tasks/0044_193_44193489_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_193_44193489_qa_1/tests/grader.py +++ b/tasks/0044_193_44193489_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0044_251_44251119_qa_3/tests/grader.py b/tasks/0044_251_44251119_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_251_44251119_qa_3/tests/grader.py +++ b/tasks/0044_251_44251119_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0044_412_44412230_qa_1/tests/grader.py b/tasks/0044_412_44412230_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_412_44412230_qa_1/tests/grader.py +++ b/tasks/0044_412_44412230_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0045_138_45138042_qa_4/tests/grader.py b/tasks/0045_138_45138042_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_138_45138042_qa_4/tests/grader.py +++ b/tasks/0045_138_45138042_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0045_821_45821165_qa_3/tests/grader.py b/tasks/0045_821_45821165_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_821_45821165_qa_3/tests/grader.py +++ b/tasks/0045_821_45821165_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0045_969_45969290_qa_1/tests/grader.py b/tasks/0045_969_45969290_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_969_45969290_qa_1/tests/grader.py +++ b/tasks/0045_969_45969290_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0046_955_46955725_qa_4/environment/Dockerfile b/tasks/0046_955_46955725_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0046_955_46955725_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0046_955_46955725_qa_4/environment/pull_bucket.py b/tasks/0046_955_46955725_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0046_955_46955725_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0046_955_46955725_qa_4/tests/grader.py b/tasks/0046_955_46955725_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0046_955_46955725_qa_4/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0046_955_46955725_qa_4/tests/test.sh b/tasks/0046_955_46955725_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0046_955_46955725_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0047_417_47417997_qa_3/environment/Dockerfile b/tasks/0047_417_47417997_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0047_417_47417997_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0047_417_47417997_qa_3/environment/pull_bucket.py b/tasks/0047_417_47417997_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0047_417_47417997_qa_3/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0047_417_47417997_qa_3/tests/grader.py b/tasks/0047_417_47417997_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0047_417_47417997_qa_3/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0047_417_47417997_qa_3/tests/test.sh b/tasks/0047_417_47417997_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0047_417_47417997_qa_3/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0047_852_47852416_qa_2/tests/grader.py b/tasks/0047_852_47852416_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0047_852_47852416_qa_2/tests/grader.py +++ b/tasks/0047_852_47852416_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0048_436_48436455_qa_2/tests/grader.py b/tasks/0048_436_48436455_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0048_436_48436455_qa_2/tests/grader.py +++ b/tasks/0048_436_48436455_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0049_738_49738137_qa_4/tests/grader.py b/tasks/0049_738_49738137_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_738_49738137_qa_4/tests/grader.py +++ b/tasks/0049_738_49738137_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0049_738_49738137_qa_5/tests/grader.py b/tasks/0049_738_49738137_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_738_49738137_qa_5/tests/grader.py +++ b/tasks/0049_738_49738137_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0049_804_49804423_qa_2/tests/grader.py b/tasks/0049_804_49804423_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_804_49804423_qa_2/tests/grader.py +++ b/tasks/0049_804_49804423_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0050_224_50224594_qa_5/tests/grader.py b/tasks/0050_224_50224594_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0050_224_50224594_qa_5/tests/grader.py +++ b/tasks/0050_224_50224594_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0051_525_51525477_qa_1/tests/grader.py b/tasks/0051_525_51525477_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_525_51525477_qa_1/tests/grader.py +++ b/tasks/0051_525_51525477_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0051_529_51529879_qa_4/tests/grader.py b/tasks/0051_529_51529879_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_529_51529879_qa_4/tests/grader.py +++ b/tasks/0051_529_51529879_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0051_975_51975834_qa_4/tests/grader.py b/tasks/0051_975_51975834_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_975_51975834_qa_4/tests/grader.py +++ b/tasks/0051_975_51975834_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0052_471_52471814_qa_1/tests/grader.py b/tasks/0052_471_52471814_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_471_52471814_qa_1/tests/grader.py +++ b/tasks/0052_471_52471814_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0053_327_53327790_qa_3/tests/grader.py b/tasks/0053_327_53327790_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_327_53327790_qa_3/tests/grader.py +++ b/tasks/0053_327_53327790_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0053_352_53352624_qa_1/tests/grader.py b/tasks/0053_352_53352624_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_352_53352624_qa_1/tests/grader.py +++ b/tasks/0053_352_53352624_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0053_426_53426290_qa_3/tests/grader.py b/tasks/0053_426_53426290_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_426_53426290_qa_3/tests/grader.py +++ b/tasks/0053_426_53426290_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0053_426_53426290_qa_5/tests/grader.py b/tasks/0053_426_53426290_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_426_53426290_qa_5/tests/grader.py +++ b/tasks/0053_426_53426290_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0054_315_54315694_qa_2/tests/grader.py b/tasks/0054_315_54315694_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_315_54315694_qa_2/tests/grader.py +++ b/tasks/0054_315_54315694_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0054_739_54739768_qa_1/tests/grader.py b/tasks/0054_739_54739768_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_739_54739768_qa_1/tests/grader.py +++ b/tasks/0054_739_54739768_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0054_801_54801630_qa_2/tests/grader.py b/tasks/0054_801_54801630_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_801_54801630_qa_2/tests/grader.py +++ b/tasks/0054_801_54801630_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0055_790_55790118_qa_2/tests/grader.py b/tasks/0055_790_55790118_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_790_55790118_qa_2/tests/grader.py +++ b/tasks/0055_790_55790118_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0055_790_55790118_qa_3/tests/grader.py b/tasks/0055_790_55790118_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_790_55790118_qa_3/tests/grader.py +++ b/tasks/0055_790_55790118_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0055_824_55824440_qa_3/tests/grader.py b/tasks/0055_824_55824440_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_824_55824440_qa_3/tests/grader.py +++ b/tasks/0055_824_55824440_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0056_687_56687302_qa_2/tests/grader.py b/tasks/0056_687_56687302_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_687_56687302_qa_2/tests/grader.py +++ b/tasks/0056_687_56687302_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0056_907_56907084_qa_3/tests/grader.py b/tasks/0056_907_56907084_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_907_56907084_qa_3/tests/grader.py +++ b/tasks/0056_907_56907084_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0059_523_59523535_qa_3/tests/grader.py b/tasks/0059_523_59523535_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0059_523_59523535_qa_3/tests/grader.py +++ b/tasks/0059_523_59523535_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0061_998_61998767_qa_3/tests/grader.py b/tasks/0061_998_61998767_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_998_61998767_qa_3/tests/grader.py +++ b/tasks/0061_998_61998767_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0062_391_62391096_qa_3/tests/grader.py b/tasks/0062_391_62391096_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0062_391_62391096_qa_3/tests/grader.py +++ b/tasks/0062_391_62391096_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0063_056_63056064_qa_2/tests/grader.py b/tasks/0063_056_63056064_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_056_63056064_qa_2/tests/grader.py +++ b/tasks/0063_056_63056064_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0063_350_63350967_qa_3/tests/grader.py b/tasks/0063_350_63350967_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_350_63350967_qa_3/tests/grader.py +++ b/tasks/0063_350_63350967_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0064_698_64698192_qa_1/tests/grader.py b/tasks/0064_698_64698192_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_698_64698192_qa_1/tests/grader.py +++ b/tasks/0064_698_64698192_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0064_983_64983007_qa_2/tests/grader.py b/tasks/0064_983_64983007_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_983_64983007_qa_2/tests/grader.py +++ b/tasks/0064_983_64983007_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_162_65162734_qa_3/tests/grader.py b/tasks/0065_162_65162734_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_162_65162734_qa_3/tests/grader.py +++ b/tasks/0065_162_65162734_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_262_65262139_qa_4/tests/grader.py b/tasks/0065_262_65262139_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_262_65262139_qa_4/tests/grader.py +++ b/tasks/0065_262_65262139_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_495_65495142_qa_3/tests/grader.py b/tasks/0065_495_65495142_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_495_65495142_qa_3/tests/grader.py +++ b/tasks/0065_495_65495142_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_504_65504512_qa_3/tests/grader.py b/tasks/0065_504_65504512_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_504_65504512_qa_3/tests/grader.py +++ b/tasks/0065_504_65504512_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_563_65563185_qa_4/tests/grader.py b/tasks/0065_563_65563185_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_563_65563185_qa_4/tests/grader.py +++ b/tasks/0065_563_65563185_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_745_65745045_qa_1/tests/grader.py b/tasks/0065_745_65745045_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_745_65745045_qa_1/tests/grader.py +++ b/tasks/0065_745_65745045_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_794_65794937_qa_5/tests/grader.py b/tasks/0065_794_65794937_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_794_65794937_qa_5/tests/grader.py +++ b/tasks/0065_794_65794937_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0066_107_66107048_qa_4/tests/grader.py b/tasks/0066_107_66107048_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0066_107_66107048_qa_4/tests/grader.py +++ b/tasks/0066_107_66107048_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0066_372_66372058_qa_2/environment/Dockerfile b/tasks/0066_372_66372058_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0066_372_66372058_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0066_372_66372058_qa_2/environment/pull_bucket.py b/tasks/0066_372_66372058_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0066_372_66372058_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0066_372_66372058_qa_2/tests/grader.py b/tasks/0066_372_66372058_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0066_372_66372058_qa_2/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0066_372_66372058_qa_2/tests/test.sh b/tasks/0066_372_66372058_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0066_372_66372058_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0066_372_66372058_qa_4/tests/grader.py b/tasks/0066_372_66372058_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0066_372_66372058_qa_4/tests/grader.py +++ b/tasks/0066_372_66372058_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0067_225_67225548_qa_5/tests/grader.py b/tasks/0067_225_67225548_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_225_67225548_qa_5/tests/grader.py +++ b/tasks/0067_225_67225548_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0067_657_67657879_qa_3/tests/grader.py b/tasks/0067_657_67657879_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_657_67657879_qa_3/tests/grader.py +++ b/tasks/0067_657_67657879_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0067_958_67958597_qa_5/tests/grader.py b/tasks/0067_958_67958597_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_958_67958597_qa_5/tests/grader.py +++ b/tasks/0067_958_67958597_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0068_960_68960212_qa_3/tests/grader.py b/tasks/0068_960_68960212_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_960_68960212_qa_3/tests/grader.py +++ b/tasks/0068_960_68960212_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0068_960_68960212_qa_4/tests/grader.py b/tasks/0068_960_68960212_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_960_68960212_qa_4/tests/grader.py +++ b/tasks/0068_960_68960212_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0069_054_69054524_qa_1/tests/grader.py b/tasks/0069_054_69054524_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_054_69054524_qa_1/tests/grader.py +++ b/tasks/0069_054_69054524_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0069_643_69643958_qa_2/tests/grader.py b/tasks/0069_643_69643958_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_643_69643958_qa_2/tests/grader.py +++ b/tasks/0069_643_69643958_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0072_789_72789077_qa_4/environment/Dockerfile b/tasks/0072_789_72789077_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0072_789_72789077_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0072_789_72789077_qa_4/environment/pull_bucket.py b/tasks/0072_789_72789077_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0072_789_72789077_qa_4/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0072_789_72789077_qa_4/tests/grader.py b/tasks/0072_789_72789077_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0072_789_72789077_qa_4/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0072_789_72789077_qa_4/tests/test.sh b/tasks/0072_789_72789077_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0072_789_72789077_qa_4/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0073_439_73439547_qa_3/tests/grader.py b/tasks/0073_439_73439547_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_439_73439547_qa_3/tests/grader.py +++ b/tasks/0073_439_73439547_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0074_013_74013118_qa_3/tests/grader.py b/tasks/0074_013_74013118_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_013_74013118_qa_3/tests/grader.py +++ b/tasks/0074_013_74013118_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0074_776_74776615_qa_1/tests/grader.py b/tasks/0074_776_74776615_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_776_74776615_qa_1/tests/grader.py +++ b/tasks/0074_776_74776615_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0075_890_75890673_qa_4/tests/grader.py b/tasks/0075_890_75890673_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_890_75890673_qa_4/tests/grader.py +++ b/tasks/0075_890_75890673_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0077_100_77100984_qa_2/tests/grader.py b/tasks/0077_100_77100984_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_100_77100984_qa_2/tests/grader.py +++ b/tasks/0077_100_77100984_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0077_529_77529364_qa_3/tests/grader.py b/tasks/0077_529_77529364_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_529_77529364_qa_3/tests/grader.py +++ b/tasks/0077_529_77529364_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0077_578_77578267_qa_4/tests/grader.py b/tasks/0077_578_77578267_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_578_77578267_qa_4/tests/grader.py +++ b/tasks/0077_578_77578267_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0077_684_77684454_qa_2/tests/grader.py b/tasks/0077_684_77684454_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_684_77684454_qa_2/tests/grader.py +++ b/tasks/0077_684_77684454_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0077_800_77800758_qa_5/tests/grader.py b/tasks/0077_800_77800758_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_800_77800758_qa_5/tests/grader.py +++ b/tasks/0077_800_77800758_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0079_455_79455690_qa_1/environment/Dockerfile b/tasks/0079_455_79455690_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0079_455_79455690_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0079_455_79455690_qa_1/environment/pull_bucket.py b/tasks/0079_455_79455690_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0079_455_79455690_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0079_455_79455690_qa_1/tests/grader.py b/tasks/0079_455_79455690_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0079_455_79455690_qa_1/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0079_455_79455690_qa_1/tests/test.sh b/tasks/0079_455_79455690_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0079_455_79455690_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0079_597_79597687_qa_2/tests/grader.py b/tasks/0079_597_79597687_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0079_597_79597687_qa_2/tests/grader.py +++ b/tasks/0079_597_79597687_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0079_597_79597687_qa_5/tests/grader.py b/tasks/0079_597_79597687_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0079_597_79597687_qa_5/tests/grader.py +++ b/tasks/0079_597_79597687_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0079_852_79852470_qa_3/tests/grader.py b/tasks/0079_852_79852470_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0079_852_79852470_qa_3/tests/grader.py +++ b/tasks/0079_852_79852470_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0079_852_79852470_qa_4/tests/grader.py b/tasks/0079_852_79852470_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0079_852_79852470_qa_4/tests/grader.py +++ b/tasks/0079_852_79852470_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0080_011_80011409_qa_2/tests/grader.py b/tasks/0080_011_80011409_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0080_011_80011409_qa_2/tests/grader.py +++ b/tasks/0080_011_80011409_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0080_011_80011409_qa_3/tests/grader.py b/tasks/0080_011_80011409_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0080_011_80011409_qa_3/tests/grader.py +++ b/tasks/0080_011_80011409_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0080_011_80011409_qa_4/tests/grader.py b/tasks/0080_011_80011409_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0080_011_80011409_qa_4/tests/grader.py +++ b/tasks/0080_011_80011409_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0080_200_80200515_qa_3/tests/grader.py b/tasks/0080_200_80200515_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0080_200_80200515_qa_3/tests/grader.py +++ b/tasks/0080_200_80200515_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0081_468_81468620_qa_4/tests/grader.py b/tasks/0081_468_81468620_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0081_468_81468620_qa_4/tests/grader.py +++ b/tasks/0081_468_81468620_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0086_529_86529090_qa_1/tests/grader.py b/tasks/0086_529_86529090_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0086_529_86529090_qa_1/tests/grader.py +++ b/tasks/0086_529_86529090_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0087_024_87024626_qa_4/tests/grader.py b/tasks/0087_024_87024626_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_024_87024626_qa_4/tests/grader.py +++ b/tasks/0087_024_87024626_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0087_349_87349607_qa_1/tests/grader.py b/tasks/0087_349_87349607_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_349_87349607_qa_1/tests/grader.py +++ b/tasks/0087_349_87349607_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0087_893_87893220_qa_2/tests/grader.py b/tasks/0087_893_87893220_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_893_87893220_qa_2/tests/grader.py +++ b/tasks/0087_893_87893220_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0088_108_88108629_qa_1/tests/grader.py b/tasks/0088_108_88108629_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0088_108_88108629_qa_1/tests/grader.py +++ b/tasks/0088_108_88108629_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0088_214_88214420_qa_3/tests/grader.py b/tasks/0088_214_88214420_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0088_214_88214420_qa_3/tests/grader.py +++ b/tasks/0088_214_88214420_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0088_996_88996860_qa_1/tests/grader.py b/tasks/0088_996_88996860_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0088_996_88996860_qa_1/tests/grader.py +++ b/tasks/0088_996_88996860_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0089_547_89547343_qa_2/tests/grader.py b/tasks/0089_547_89547343_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0089_547_89547343_qa_2/tests/grader.py +++ b/tasks/0089_547_89547343_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0091_861_91861304_qa_1/tests/grader.py b/tasks/0091_861_91861304_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_861_91861304_qa_1/tests/grader.py +++ b/tasks/0091_861_91861304_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0094_622_94622632_qa_2/tests/grader.py b/tasks/0094_622_94622632_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0094_622_94622632_qa_2/tests/grader.py +++ b/tasks/0094_622_94622632_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0095_088_95088024_qa_1/tests/grader.py b/tasks/0095_088_95088024_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0095_088_95088024_qa_1/tests/grader.py +++ b/tasks/0095_088_95088024_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0095_344_95344142_qa_3/tests/grader.py b/tasks/0095_344_95344142_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0095_344_95344142_qa_3/tests/grader.py +++ b/tasks/0095_344_95344142_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0095_344_95344142_qa_4/tests/grader.py b/tasks/0095_344_95344142_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0095_344_95344142_qa_4/tests/grader.py +++ b/tasks/0095_344_95344142_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0096_064_96064872_qa_1/tests/grader.py b/tasks/0096_064_96064872_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0096_064_96064872_qa_1/tests/grader.py +++ b/tasks/0096_064_96064872_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0096_889_96889516_qa_4/tests/grader.py b/tasks/0096_889_96889516_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0096_889_96889516_qa_4/tests/grader.py +++ b/tasks/0096_889_96889516_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0096_889_96889516_qa_5/tests/grader.py b/tasks/0096_889_96889516_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0096_889_96889516_qa_5/tests/grader.py +++ b/tasks/0096_889_96889516_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0097_809_97809761_qa_2/tests/grader.py b/tasks/0097_809_97809761_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0097_809_97809761_qa_2/tests/grader.py +++ b/tasks/0097_809_97809761_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0098_910_98910010_qa_4/tests/grader.py b/tasks/0098_910_98910010_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0098_910_98910010_qa_4/tests/grader.py +++ b/tasks/0098_910_98910010_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0099_705_99705765_qa_5/tests/grader.py b/tasks/0099_705_99705765_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0099_705_99705765_qa_5/tests/grader.py +++ b/tasks/0099_705_99705765_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0099_730_99730639_qa_2/tests/grader.py b/tasks/0099_730_99730639_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0099_730_99730639_qa_2/tests/grader.py +++ b/tasks/0099_730_99730639_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0100_668_100668614_qa_1/tests/grader.py b/tasks/0100_668_100668614_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0100_668_100668614_qa_1/tests/grader.py +++ b/tasks/0100_668_100668614_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0100_729_100729925_qa_4/tests/grader.py b/tasks/0100_729_100729925_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0100_729_100729925_qa_4/tests/grader.py +++ b/tasks/0100_729_100729925_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0101_296_101296258_qa_3/tests/grader.py b/tasks/0101_296_101296258_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0101_296_101296258_qa_3/tests/grader.py +++ b/tasks/0101_296_101296258_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0101_507_101507712_qa_1/tests/grader.py b/tasks/0101_507_101507712_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0101_507_101507712_qa_1/tests/grader.py +++ b/tasks/0101_507_101507712_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0101_773_101773827_qa_4/tests/grader.py b/tasks/0101_773_101773827_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0101_773_101773827_qa_4/tests/grader.py +++ b/tasks/0101_773_101773827_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0102_198_102198537_qa_5/tests/grader.py b/tasks/0102_198_102198537_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_198_102198537_qa_5/tests/grader.py +++ b/tasks/0102_198_102198537_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0102_377_102377716_qa_4/tests/grader.py b/tasks/0102_377_102377716_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_377_102377716_qa_4/tests/grader.py +++ b/tasks/0102_377_102377716_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0102_982_102982156_qa_3/tests/grader.py b/tasks/0102_982_102982156_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_982_102982156_qa_3/tests/grader.py +++ b/tasks/0102_982_102982156_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0102_982_102982156_qa_4/tests/grader.py b/tasks/0102_982_102982156_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_982_102982156_qa_4/tests/grader.py +++ b/tasks/0102_982_102982156_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0103_290_103290674_qa_3/tests/grader.py b/tasks/0103_290_103290674_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_290_103290674_qa_3/tests/grader.py +++ b/tasks/0103_290_103290674_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0103_290_103290674_qa_4/tests/grader.py b/tasks/0103_290_103290674_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_290_103290674_qa_4/tests/grader.py +++ b/tasks/0103_290_103290674_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0103_884_103884351_qa_1/tests/grader.py b/tasks/0103_884_103884351_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_884_103884351_qa_1/tests/grader.py +++ b/tasks/0103_884_103884351_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0104_194_104194599_qa_4/tests/grader.py b/tasks/0104_194_104194599_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_194_104194599_qa_4/tests/grader.py +++ b/tasks/0104_194_104194599_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0104_261_104261356_qa_5/tests/grader.py b/tasks/0104_261_104261356_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_261_104261356_qa_5/tests/grader.py +++ b/tasks/0104_261_104261356_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0108_284_108284561_qa_2/tests/grader.py b/tasks/0108_284_108284561_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0108_284_108284561_qa_2/tests/grader.py +++ b/tasks/0108_284_108284561_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0109_269_109269793_qa_5/tests/grader.py b/tasks/0109_269_109269793_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0109_269_109269793_qa_5/tests/grader.py +++ b/tasks/0109_269_109269793_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0110_531_110531781_qa_1/tests/grader.py b/tasks/0110_531_110531781_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_531_110531781_qa_1/tests/grader.py +++ b/tasks/0110_531_110531781_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0110_597_110597362_qa_1/tests/grader.py b/tasks/0110_597_110597362_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_597_110597362_qa_1/tests/grader.py +++ b/tasks/0110_597_110597362_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0110_612_110612327_qa_4/tests/grader.py b/tasks/0110_612_110612327_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_612_110612327_qa_4/tests/grader.py +++ b/tasks/0110_612_110612327_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0111_139_111139616_qa_2/tests/grader.py b/tasks/0111_139_111139616_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0111_139_111139616_qa_2/tests/grader.py +++ b/tasks/0111_139_111139616_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0111_721_111721771_qa_5/tests/grader.py b/tasks/0111_721_111721771_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0111_721_111721771_qa_5/tests/grader.py +++ b/tasks/0111_721_111721771_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0112_857_112857611_qa_4/tests/grader.py b/tasks/0112_857_112857611_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0112_857_112857611_qa_4/tests/grader.py +++ b/tasks/0112_857_112857611_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0112_857_112857611_qa_5/environment/Dockerfile b/tasks/0112_857_112857611_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0112_857_112857611_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0112_857_112857611_qa_5/environment/pull_bucket.py b/tasks/0112_857_112857611_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0112_857_112857611_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0112_857_112857611_qa_5/tests/grader.py b/tasks/0112_857_112857611_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0112_857_112857611_qa_5/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0112_857_112857611_qa_5/tests/test.sh b/tasks/0112_857_112857611_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0112_857_112857611_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0114_908_114908217_qa_4/tests/grader.py b/tasks/0114_908_114908217_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0114_908_114908217_qa_4/tests/grader.py +++ b/tasks/0114_908_114908217_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0115_266_115266605_qa_3/tests/grader.py b/tasks/0115_266_115266605_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_266_115266605_qa_3/tests/grader.py +++ b/tasks/0115_266_115266605_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0115_266_115266605_qa_4/tests/grader.py b/tasks/0115_266_115266605_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_266_115266605_qa_4/tests/grader.py +++ b/tasks/0115_266_115266605_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0119_178_119178142_qa_4/tests/grader.py b/tasks/0119_178_119178142_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_178_119178142_qa_4/tests/grader.py +++ b/tasks/0119_178_119178142_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0119_277_119277434_qa_4/tests/grader.py b/tasks/0119_277_119277434_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_277_119277434_qa_4/tests/grader.py +++ b/tasks/0119_277_119277434_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0119_926_119926274_qa_5/tests/grader.py b/tasks/0119_926_119926274_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_926_119926274_qa_5/tests/grader.py +++ b/tasks/0119_926_119926274_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0120_525_120525884_qa_4/tests/grader.py b/tasks/0120_525_120525884_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0120_525_120525884_qa_4/tests/grader.py +++ b/tasks/0120_525_120525884_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0120_687_120687537_qa_5/environment/Dockerfile b/tasks/0120_687_120687537_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0120_687_120687537_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0120_687_120687537_qa_5/environment/pull_bucket.py b/tasks/0120_687_120687537_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0120_687_120687537_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0120_687_120687537_qa_5/tests/grader.py b/tasks/0120_687_120687537_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0120_687_120687537_qa_5/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0120_687_120687537_qa_5/tests/test.sh b/tasks/0120_687_120687537_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0120_687_120687537_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0121_143_121143084_qa_3/tests/grader.py b/tasks/0121_143_121143084_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0121_143_121143084_qa_3/tests/grader.py +++ b/tasks/0121_143_121143084_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0121_209_121209389_qa_1/tests/grader.py b/tasks/0121_209_121209389_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0121_209_121209389_qa_1/tests/grader.py +++ b/tasks/0121_209_121209389_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0121_947_121947601_qa_1/environment/Dockerfile b/tasks/0121_947_121947601_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0121_947_121947601_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0121_947_121947601_qa_1/environment/pull_bucket.py b/tasks/0121_947_121947601_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0121_947_121947601_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0121_947_121947601_qa_1/tests/grader.py b/tasks/0121_947_121947601_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0121_947_121947601_qa_1/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0121_947_121947601_qa_1/tests/test.sh b/tasks/0121_947_121947601_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0121_947_121947601_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0122_394_122394666_qa_1/tests/grader.py b/tasks/0122_394_122394666_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0122_394_122394666_qa_1/tests/grader.py +++ b/tasks/0122_394_122394666_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0122_517_122517438_qa_3/tests/grader.py b/tasks/0122_517_122517438_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0122_517_122517438_qa_3/tests/grader.py +++ b/tasks/0122_517_122517438_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0123_735_123735039_qa_5/tests/grader.py b/tasks/0123_735_123735039_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_735_123735039_qa_5/tests/grader.py +++ b/tasks/0123_735_123735039_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0124_739_124739657_qa_1/tests/grader.py b/tasks/0124_739_124739657_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0124_739_124739657_qa_1/tests/grader.py +++ b/tasks/0124_739_124739657_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0125_624_125624875_qa_1/tests/grader.py b/tasks/0125_624_125624875_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0125_624_125624875_qa_1/tests/grader.py +++ b/tasks/0125_624_125624875_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0128_624_128624067_qa_3/tests/grader.py b/tasks/0128_624_128624067_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0128_624_128624067_qa_3/tests/grader.py +++ b/tasks/0128_624_128624067_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0129_211_129211866_qa_3/tests/grader.py b/tasks/0129_211_129211866_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0129_211_129211866_qa_3/tests/grader.py +++ b/tasks/0129_211_129211866_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0129_395_129395519_qa_2/environment/Dockerfile b/tasks/0129_395_129395519_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0129_395_129395519_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0129_395_129395519_qa_2/environment/pull_bucket.py b/tasks/0129_395_129395519_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0129_395_129395519_qa_2/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0129_395_129395519_qa_2/tests/grader.py b/tasks/0129_395_129395519_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0129_395_129395519_qa_2/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0129_395_129395519_qa_2/tests/test.sh b/tasks/0129_395_129395519_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0129_395_129395519_qa_2/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0129_786_129786687_qa_5/tests/grader.py b/tasks/0129_786_129786687_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0129_786_129786687_qa_5/tests/grader.py +++ b/tasks/0129_786_129786687_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0130_890_130890369_qa_2/tests/grader.py b/tasks/0130_890_130890369_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0130_890_130890369_qa_2/tests/grader.py +++ b/tasks/0130_890_130890369_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0131_609_131609730_qa_1/tests/grader.py b/tasks/0131_609_131609730_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0131_609_131609730_qa_1/tests/grader.py +++ b/tasks/0131_609_131609730_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0132_151_132151183_qa_1/tests/grader.py b/tasks/0132_151_132151183_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_151_132151183_qa_1/tests/grader.py +++ b/tasks/0132_151_132151183_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0132_270_132270430_qa_4/tests/grader.py b/tasks/0132_270_132270430_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_270_132270430_qa_4/tests/grader.py +++ b/tasks/0132_270_132270430_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0132_624_132624870_qa_5/environment/Dockerfile b/tasks/0132_624_132624870_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0132_624_132624870_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0132_624_132624870_qa_5/environment/pull_bucket.py b/tasks/0132_624_132624870_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0132_624_132624870_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0132_624_132624870_qa_5/tests/grader.py b/tasks/0132_624_132624870_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0132_624_132624870_qa_5/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0132_624_132624870_qa_5/tests/test.sh b/tasks/0132_624_132624870_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0132_624_132624870_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0133_909_133909373_qa_3/tests/grader.py b/tasks/0133_909_133909373_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0133_909_133909373_qa_3/tests/grader.py +++ b/tasks/0133_909_133909373_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0135_920_135920645_qa_4/tests/grader.py b/tasks/0135_920_135920645_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_920_135920645_qa_4/tests/grader.py +++ b/tasks/0135_920_135920645_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0136_053_136053251_qa_2/tests/grader.py b/tasks/0136_053_136053251_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0136_053_136053251_qa_2/tests/grader.py +++ b/tasks/0136_053_136053251_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0136_053_136053251_qa_4/tests/grader.py b/tasks/0136_053_136053251_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0136_053_136053251_qa_4/tests/grader.py +++ b/tasks/0136_053_136053251_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0136_242_136242885_qa_2/tests/grader.py b/tasks/0136_242_136242885_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0136_242_136242885_qa_2/tests/grader.py +++ b/tasks/0136_242_136242885_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0136_483_136483047_qa_4/tests/grader.py b/tasks/0136_483_136483047_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0136_483_136483047_qa_4/tests/grader.py +++ b/tasks/0136_483_136483047_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0136_825_136825945_qa_1/environment/Dockerfile b/tasks/0136_825_136825945_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0136_825_136825945_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0136_825_136825945_qa_1/environment/pull_bucket.py b/tasks/0136_825_136825945_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0136_825_136825945_qa_1/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0136_825_136825945_qa_1/tests/grader.py b/tasks/0136_825_136825945_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0136_825_136825945_qa_1/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0136_825_136825945_qa_1/tests/test.sh b/tasks/0136_825_136825945_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0136_825_136825945_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0137_769_137769141_qa_3/tests/grader.py b/tasks/0137_769_137769141_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0137_769_137769141_qa_3/tests/grader.py +++ b/tasks/0137_769_137769141_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0137_769_137769141_qa_5/tests/grader.py b/tasks/0137_769_137769141_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0137_769_137769141_qa_5/tests/grader.py +++ b/tasks/0137_769_137769141_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0138_755_138755530_qa_2/tests/grader.py b/tasks/0138_755_138755530_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0138_755_138755530_qa_2/tests/grader.py +++ b/tasks/0138_755_138755530_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0139_186_139186690_qa_5/tests/grader.py b/tasks/0139_186_139186690_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_186_139186690_qa_5/tests/grader.py +++ b/tasks/0139_186_139186690_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0