diff --git a/tasks/0000_886_886039_qa_2/tests/grader.py b/tasks/0000_886_886039_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0000_886_886039_qa_2/tests/grader.py +++ b/tasks/0000_886_886039_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_181_1181828_qa_4/tests/grader.py b/tasks/0001_181_1181828_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_181_1181828_qa_4/tests/grader.py +++ b/tasks/0001_181_1181828_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_238_1238370_qa_1/tests/grader.py b/tasks/0001_238_1238370_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_238_1238370_qa_1/tests/grader.py +++ b/tasks/0001_238_1238370_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_473_1473187_qa_1/tests/grader.py b/tasks/0001_473_1473187_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_473_1473187_qa_1/tests/grader.py +++ b/tasks/0001_473_1473187_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/0001_521_1521206_qa_2/tests/grader.py b/tasks/0001_521_1521206_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_521_1521206_qa_2/tests/grader.py +++ b/tasks/0001_521_1521206_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_522_1522371_qa_5/tests/grader.py b/tasks/0001_522_1522371_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_522_1522371_qa_5/tests/grader.py +++ b/tasks/0001_522_1522371_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_527_1527039_qa_2/tests/grader.py b/tasks/0001_527_1527039_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_527_1527039_qa_2/tests/grader.py +++ b/tasks/0001_527_1527039_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_541_1541002_qa_2/tests/grader.py b/tasks/0001_541_1541002_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_541_1541002_qa_2/tests/grader.py +++ b/tasks/0001_541_1541002_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_570_1570948_qa_4/tests/grader.py b/tasks/0001_570_1570948_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_570_1570948_qa_4/tests/grader.py +++ b/tasks/0001_570_1570948_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_661_1661005_qa_1/tests/grader.py b/tasks/0001_661_1661005_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_661_1661005_qa_1/tests/grader.py +++ b/tasks/0001_661_1661005_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_666_1666101_qa_5/tests/grader.py b/tasks/0001_666_1666101_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_666_1666101_qa_5/tests/grader.py +++ b/tasks/0001_666_1666101_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_876_1876377_qa_2/tests/grader.py b/tasks/0001_876_1876377_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_876_1876377_qa_2/tests/grader.py +++ b/tasks/0001_876_1876377_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_959_1959663_qa_3/tests/grader.py b/tasks/0001_959_1959663_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_959_1959663_qa_3/tests/grader.py +++ b/tasks/0001_959_1959663_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/0002_094_2094844_qa_1/tests/grader.py b/tasks/0002_094_2094844_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_094_2094844_qa_1/tests/grader.py +++ b/tasks/0002_094_2094844_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/0002_203_2203940_qa_5/environment/Dockerfile b/tasks/0002_203_2203940_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0002_203_2203940_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0002_203_2203940_qa_5/environment/pull_bucket.py b/tasks/0002_203_2203940_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0002_203_2203940_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/0002_203_2203940_qa_5/tests/grader.py b/tasks/0002_203_2203940_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0002_203_2203940_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/0002_203_2203940_qa_5/tests/test.sh b/tasks/0002_203_2203940_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0002_203_2203940_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/0002_219_2219893_qa_3/tests/grader.py b/tasks/0002_219_2219893_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_219_2219893_qa_3/tests/grader.py +++ b/tasks/0002_219_2219893_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/0010_909_10909980_qa_3/tests/grader.py b/tasks/0010_909_10909980_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0010_909_10909980_qa_3/tests/grader.py +++ b/tasks/0010_909_10909980_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/0011_970_11970593_qa_2/tests/grader.py b/tasks/0011_970_11970593_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0011_970_11970593_qa_2/tests/grader.py +++ b/tasks/0011_970_11970593_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_081_13081725_qa_3/tests/grader.py b/tasks/0013_081_13081725_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_081_13081725_qa_3/tests/grader.py +++ b/tasks/0013_081_13081725_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/0013_604_13604091_qa_2/tests/grader.py b/tasks/0013_604_13604091_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_604_13604091_qa_2/tests/grader.py +++ b/tasks/0013_604_13604091_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_733_13733964_qa_1/tests/grader.py b/tasks/0013_733_13733964_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_733_13733964_qa_1/tests/grader.py +++ b/tasks/0013_733_13733964_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/0013_884_13884693_qa_1/tests/grader.py b/tasks/0013_884_13884693_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_884_13884693_qa_1/tests/grader.py +++ b/tasks/0013_884_13884693_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/0013_911_13911248_qa_1/tests/grader.py b/tasks/0013_911_13911248_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_911_13911248_qa_1/tests/grader.py +++ b/tasks/0013_911_13911248_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/0014_089_14089673_qa_5/tests/grader.py b/tasks/0014_089_14089673_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0014_089_14089673_qa_5/tests/grader.py +++ b/tasks/0014_089_14089673_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/0014_469_14469283_qa_3/tests/grader.py b/tasks/0014_469_14469283_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0014_469_14469283_qa_3/tests/grader.py +++ b/tasks/0014_469_14469283_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/0014_469_14469283_qa_4/tests/grader.py b/tasks/0014_469_14469283_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0014_469_14469283_qa_4/tests/grader.py +++ b/tasks/0014_469_14469283_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/0014_933_14933483_qa_2/tests/grader.py b/tasks/0014_933_14933483_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0014_933_14933483_qa_2/tests/grader.py +++ b/tasks/0014_933_14933483_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/0015_050_15050710_qa_1/tests/grader.py b/tasks/0015_050_15050710_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0015_050_15050710_qa_1/tests/grader.py +++ b/tasks/0015_050_15050710_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/0018_456_18456045_qa_5/tests/grader.py b/tasks/0018_456_18456045_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0018_456_18456045_qa_5/tests/grader.py +++ b/tasks/0018_456_18456045_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/0018_493_18493579_qa_1/tests/grader.py b/tasks/0018_493_18493579_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0018_493_18493579_qa_1/tests/grader.py +++ b/tasks/0018_493_18493579_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/0020_216_20216126_qa_2/tests/grader.py b/tasks/0020_216_20216126_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_216_20216126_qa_2/tests/grader.py +++ b/tasks/0020_216_20216126_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/0020_613_20613845_qa_4/tests/grader.py b/tasks/0020_613_20613845_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_613_20613845_qa_4/tests/grader.py +++ b/tasks/0020_613_20613845_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/0020_756_20756026_qa_2/tests/grader.py b/tasks/0020_756_20756026_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_756_20756026_qa_2/tests/grader.py +++ b/tasks/0020_756_20756026_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/0021_299_21299002_qa_3/tests/grader.py b/tasks/0021_299_21299002_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_299_21299002_qa_3/tests/grader.py +++ b/tasks/0021_299_21299002_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/0022_193_22193578_qa_5/environment/Dockerfile b/tasks/0022_193_22193578_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0022_193_22193578_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0022_193_22193578_qa_5/environment/pull_bucket.py b/tasks/0022_193_22193578_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0022_193_22193578_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/0022_193_22193578_qa_5/tests/grader.py b/tasks/0022_193_22193578_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0022_193_22193578_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/0022_193_22193578_qa_5/tests/test.sh b/tasks/0022_193_22193578_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0022_193_22193578_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/0022_916_22916338_qa_5/tests/grader.py b/tasks/0022_916_22916338_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0022_916_22916338_qa_5/tests/grader.py +++ b/tasks/0022_916_22916338_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/0023_468_23468316_qa_3/tests/grader.py b/tasks/0023_468_23468316_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_468_23468316_qa_3/tests/grader.py +++ b/tasks/0023_468_23468316_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/0023_583_23583710_qa_4/tests/grader.py b/tasks/0023_583_23583710_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_583_23583710_qa_4/tests/grader.py +++ b/tasks/0023_583_23583710_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_598_23598239_qa_1/tests/grader.py b/tasks/0023_598_23598239_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_598_23598239_qa_1/tests/grader.py +++ b/tasks/0023_598_23598239_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/0023_931_23931431_qa_1/tests/grader.py b/tasks/0023_931_23931431_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_931_23931431_qa_1/tests/grader.py +++ b/tasks/0023_931_23931431_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_069_24069916_qa_1/tests/grader.py b/tasks/0024_069_24069916_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_069_24069916_qa_1/tests/grader.py +++ b/tasks/0024_069_24069916_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_275_24275657_qa_5/environment/Dockerfile b/tasks/0024_275_24275657_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0024_275_24275657_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0024_275_24275657_qa_5/environment/pull_bucket.py b/tasks/0024_275_24275657_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0024_275_24275657_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/0024_275_24275657_qa_5/tests/grader.py b/tasks/0024_275_24275657_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0024_275_24275657_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/0024_275_24275657_qa_5/tests/test.sh b/tasks/0024_275_24275657_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0024_275_24275657_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/0025_204_25204322_qa_4/tests/grader.py b/tasks/0025_204_25204322_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0025_204_25204322_qa_4/tests/grader.py +++ b/tasks/0025_204_25204322_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/0026_836_26836336_qa_1/tests/grader.py b/tasks/0026_836_26836336_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0026_836_26836336_qa_1/tests/grader.py +++ b/tasks/0026_836_26836336_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/0026_997_26997571_qa_2/tests/grader.py b/tasks/0026_997_26997571_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0026_997_26997571_qa_2/tests/grader.py +++ b/tasks/0026_997_26997571_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/0026_997_26997571_qa_5/tests/grader.py b/tasks/0026_997_26997571_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0026_997_26997571_qa_5/tests/grader.py +++ b/tasks/0026_997_26997571_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/0028_443_28443310_qa_4/tests/grader.py b/tasks/0028_443_28443310_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0028_443_28443310_qa_4/tests/grader.py +++ b/tasks/0028_443_28443310_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/0028_443_28443310_qa_5/tests/grader.py b/tasks/0028_443_28443310_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0028_443_28443310_qa_5/tests/grader.py +++ b/tasks/0028_443_28443310_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/0029_204_29204719_qa_2/tests/grader.py b/tasks/0029_204_29204719_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0029_204_29204719_qa_2/tests/grader.py +++ b/tasks/0029_204_29204719_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/0029_558_29558970_qa_2/tests/grader.py b/tasks/0029_558_29558970_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0029_558_29558970_qa_2/tests/grader.py +++ b/tasks/0029_558_29558970_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/0030_890_30890976_qa_4/tests/grader.py b/tasks/0030_890_30890976_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_890_30890976_qa_4/tests/grader.py +++ b/tasks/0030_890_30890976_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/0030_890_30890976_qa_5/tests/grader.py b/tasks/0030_890_30890976_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_890_30890976_qa_5/tests/grader.py +++ b/tasks/0030_890_30890976_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/0031_829_31829521_qa_1/environment/Dockerfile b/tasks/0031_829_31829521_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0031_829_31829521_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0031_829_31829521_qa_1/environment/pull_bucket.py b/tasks/0031_829_31829521_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0031_829_31829521_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/0031_829_31829521_qa_1/tests/grader.py b/tasks/0031_829_31829521_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0031_829_31829521_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/0031_829_31829521_qa_1/tests/test.sh b/tasks/0031_829_31829521_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0031_829_31829521_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/0032_211_32211559_qa_5/tests/grader.py b/tasks/0032_211_32211559_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_211_32211559_qa_5/tests/grader.py +++ b/tasks/0032_211_32211559_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/0032_386_32386426_qa_2/tests/grader.py b/tasks/0032_386_32386426_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_386_32386426_qa_2/tests/grader.py +++ b/tasks/0032_386_32386426_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/0033_684_33684962_qa_3/tests/grader.py b/tasks/0033_684_33684962_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_684_33684962_qa_3/tests/grader.py +++ b/tasks/0033_684_33684962_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/0034_339_34339717_qa_5/tests/grader.py b/tasks/0034_339_34339717_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_339_34339717_qa_5/tests/grader.py +++ b/tasks/0034_339_34339717_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/0034_380_34380054_qa_2/environment/Dockerfile b/tasks/0034_380_34380054_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0034_380_34380054_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0034_380_34380054_qa_2/environment/pull_bucket.py b/tasks/0034_380_34380054_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0034_380_34380054_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/0034_380_34380054_qa_2/tests/test.sh b/tasks/0034_380_34380054_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0034_380_34380054_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/0034_726_34726167_qa_2/tests/grader.py b/tasks/0034_726_34726167_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_726_34726167_qa_2/tests/grader.py +++ b/tasks/0034_726_34726167_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/0034_748_34748003_qa_1/tests/grader.py b/tasks/0034_748_34748003_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_748_34748003_qa_1/tests/grader.py +++ b/tasks/0034_748_34748003_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/0034_912_34912092_qa_3/tests/grader.py b/tasks/0034_912_34912092_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_912_34912092_qa_3/tests/grader.py +++ b/tasks/0034_912_34912092_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/0035_171_35171975_qa_3/tests/grader.py b/tasks/0035_171_35171975_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_171_35171975_qa_3/tests/grader.py +++ b/tasks/0035_171_35171975_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/0035_171_35171975_qa_4/tests/grader.py b/tasks/0035_171_35171975_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_171_35171975_qa_4/tests/grader.py +++ b/tasks/0035_171_35171975_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/0035_236_35236553_qa_4/tests/grader.py b/tasks/0035_236_35236553_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_236_35236553_qa_4/tests/grader.py +++ b/tasks/0035_236_35236553_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/0035_789_35789775_qa_3/tests/grader.py b/tasks/0035_789_35789775_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_789_35789775_qa_3/tests/grader.py +++ b/tasks/0035_789_35789775_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/0037_173_37173260_qa_1/tests/grader.py b/tasks/0037_173_37173260_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0037_173_37173260_qa_1/tests/grader.py +++ b/tasks/0037_173_37173260_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/0037_718_37718370_qa_1/tests/grader.py b/tasks/0037_718_37718370_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0037_718_37718370_qa_1/tests/grader.py +++ b/tasks/0037_718_37718370_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/0037_995_37995698_qa_1/tests/grader.py b/tasks/0037_995_37995698_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0037_995_37995698_qa_1/tests/grader.py +++ b/tasks/0037_995_37995698_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_821_38821052_qa_5/tests/grader.py b/tasks/0038_821_38821052_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_821_38821052_qa_5/tests/grader.py +++ b/tasks/0038_821_38821052_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/0039_243_39243552_qa_4/tests/grader.py b/tasks/0039_243_39243552_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_243_39243552_qa_4/tests/grader.py +++ b/tasks/0039_243_39243552_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/0039_409_39409376_qa_2/tests/grader.py b/tasks/0039_409_39409376_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_409_39409376_qa_2/tests/grader.py +++ b/tasks/0039_409_39409376_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/0039_512_39512601_qa_2/tests/grader.py b/tasks/0039_512_39512601_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_512_39512601_qa_2/tests/grader.py +++ b/tasks/0039_512_39512601_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/0040_298_40298967_qa_4/tests/grader.py b/tasks/0040_298_40298967_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_298_40298967_qa_4/tests/grader.py +++ b/tasks/0040_298_40298967_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/0040_298_40298967_qa_5/tests/grader.py b/tasks/0040_298_40298967_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_298_40298967_qa_5/tests/grader.py +++ b/tasks/0040_298_40298967_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/0041_015_41015677_qa_4/tests/grader.py b/tasks/0041_015_41015677_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_015_41015677_qa_4/tests/grader.py +++ b/tasks/0041_015_41015677_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/0041_020_41020843_qa_4/tests/grader.py b/tasks/0041_020_41020843_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_020_41020843_qa_4/tests/grader.py +++ b/tasks/0041_020_41020843_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/0041_321_41321221_qa_2/tests/grader.py b/tasks/0041_321_41321221_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_321_41321221_qa_2/tests/grader.py +++ b/tasks/0041_321_41321221_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_321_41321221_qa_4/tests/grader.py b/tasks/0041_321_41321221_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_321_41321221_qa_4/tests/grader.py +++ b/tasks/0041_321_41321221_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/0041_463_41463553_qa_2/tests/grader.py b/tasks/0041_463_41463553_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_463_41463553_qa_2/tests/grader.py +++ b/tasks/0041_463_41463553_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/0042_372_42372757_qa_1/tests/grader.py b/tasks/0042_372_42372757_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_372_42372757_qa_1/tests/grader.py +++ b/tasks/0042_372_42372757_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/0042_488_42488023_qa_4/tests/grader.py b/tasks/0042_488_42488023_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_488_42488023_qa_4/tests/grader.py +++ b/tasks/0042_488_42488023_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/0042_528_42528802_qa_3/tests/grader.py b/tasks/0042_528_42528802_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_528_42528802_qa_3/tests/grader.py +++ b/tasks/0042_528_42528802_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_738_42738840_qa_1/tests/grader.py b/tasks/0042_738_42738840_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_738_42738840_qa_1/tests/grader.py +++ b/tasks/0042_738_42738840_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/0042_773_42773926_qa_2/tests/grader.py b/tasks/0042_773_42773926_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_773_42773926_qa_2/tests/grader.py +++ b/tasks/0042_773_42773926_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/0042_836_42836971_qa_3/tests/grader.py b/tasks/0042_836_42836971_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_836_42836971_qa_3/tests/grader.py +++ b/tasks/0042_836_42836971_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/0042_902_42902013_qa_3/tests/grader.py b/tasks/0042_902_42902013_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_902_42902013_qa_3/tests/grader.py +++ b/tasks/0042_902_42902013_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/0043_043_43043497_qa_2/environment/Dockerfile b/tasks/0043_043_43043497_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0043_043_43043497_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0043_043_43043497_qa_2/environment/pull_bucket.py b/tasks/0043_043_43043497_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0043_043_43043497_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/0043_043_43043497_qa_2/tests/grader.py b/tasks/0043_043_43043497_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0043_043_43043497_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/0043_043_43043497_qa_2/tests/test.sh b/tasks/0043_043_43043497_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0043_043_43043497_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/0043_419_43419580_qa_2/tests/grader.py b/tasks/0043_419_43419580_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_419_43419580_qa_2/tests/grader.py +++ b/tasks/0043_419_43419580_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/0044_406_44406244_qa_1/tests/grader.py b/tasks/0044_406_44406244_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_406_44406244_qa_1/tests/grader.py +++ b/tasks/0044_406_44406244_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_727_44727189_qa_1/tests/grader.py b/tasks/0044_727_44727189_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_727_44727189_qa_1/tests/grader.py +++ b/tasks/0044_727_44727189_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/0045_454_45454053_qa_3/tests/grader.py b/tasks/0045_454_45454053_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_454_45454053_qa_3/tests/grader.py +++ b/tasks/0045_454_45454053_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/0045_605_45605559_qa_1/tests/grader.py b/tasks/0045_605_45605559_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_605_45605559_qa_1/tests/grader.py +++ b/tasks/0045_605_45605559_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_670_45670809_qa_3/tests/grader.py b/tasks/0045_670_45670809_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_670_45670809_qa_3/tests/grader.py +++ b/tasks/0045_670_45670809_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/0045_821_45821165_qa_2/tests/grader.py b/tasks/0045_821_45821165_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_821_45821165_qa_2/tests/grader.py +++ b/tasks/0045_821_45821165_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/0045_821_45821165_qa_5/tests/grader.py b/tasks/0045_821_45821165_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_821_45821165_qa_5/tests/grader.py +++ b/tasks/0045_821_45821165_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/0046_113_46113496_qa_1/tests/grader.py b/tasks/0046_113_46113496_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_113_46113496_qa_1/tests/grader.py +++ b/tasks/0046_113_46113496_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_456_46456896_qa_3/tests/grader.py b/tasks/0046_456_46456896_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_456_46456896_qa_3/tests/grader.py +++ b/tasks/0046_456_46456896_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/0046_487_46487066_qa_3/tests/grader.py b/tasks/0046_487_46487066_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_487_46487066_qa_3/tests/grader.py +++ b/tasks/0046_487_46487066_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/0046_487_46487066_qa_4/tests/grader.py b/tasks/0046_487_46487066_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_487_46487066_qa_4/tests/grader.py +++ b/tasks/0046_487_46487066_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/0046_651_46651682_qa_4/tests/grader.py b/tasks/0046_651_46651682_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_651_46651682_qa_4/tests/grader.py +++ b/tasks/0046_651_46651682_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/0046_875_46875284_qa_1/environment/Dockerfile b/tasks/0046_875_46875284_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0046_875_46875284_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0046_875_46875284_qa_1/environment/pull_bucket.py b/tasks/0046_875_46875284_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0046_875_46875284_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/0046_875_46875284_qa_1/tests/grader.py b/tasks/0046_875_46875284_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0046_875_46875284_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/0046_875_46875284_qa_1/tests/test.sh b/tasks/0046_875_46875284_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0046_875_46875284_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/0047_308_47308029_qa_1/tests/grader.py b/tasks/0047_308_47308029_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0047_308_47308029_qa_1/tests/grader.py +++ b/tasks/0047_308_47308029_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/0048_093_48093392_qa_5/environment/Dockerfile b/tasks/0048_093_48093392_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0048_093_48093392_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0048_093_48093392_qa_5/environment/pull_bucket.py b/tasks/0048_093_48093392_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0048_093_48093392_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/0048_093_48093392_qa_5/tests/grader.py b/tasks/0048_093_48093392_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0048_093_48093392_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/0048_093_48093392_qa_5/tests/test.sh b/tasks/0048_093_48093392_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0048_093_48093392_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/0048_436_48436455_qa_3/tests/grader.py b/tasks/0048_436_48436455_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0048_436_48436455_qa_3/tests/grader.py +++ b/tasks/0048_436_48436455_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/0049_018_49018627_qa_4/tests/grader.py b/tasks/0049_018_49018627_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_018_49018627_qa_4/tests/grader.py +++ b/tasks/0049_018_49018627_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/0049_482_49482971_qa_2/tests/grader.py b/tasks/0049_482_49482971_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_482_49482971_qa_2/tests/grader.py +++ b/tasks/0049_482_49482971_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_797_50797720_qa_2/tests/grader.py b/tasks/0050_797_50797720_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0050_797_50797720_qa_2/tests/grader.py +++ b/tasks/0050_797_50797720_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_797_50797720_qa_5/environment/Dockerfile b/tasks/0050_797_50797720_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0050_797_50797720_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0050_797_50797720_qa_5/environment/pull_bucket.py b/tasks/0050_797_50797720_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0050_797_50797720_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/0050_797_50797720_qa_5/tests/grader.py b/tasks/0050_797_50797720_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0050_797_50797720_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/0050_797_50797720_qa_5/tests/test.sh b/tasks/0050_797_50797720_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0050_797_50797720_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/0051_559_51559102_qa_1/tests/grader.py b/tasks/0051_559_51559102_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_559_51559102_qa_1/tests/grader.py +++ b/tasks/0051_559_51559102_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_768_51768802_qa_2/tests/grader.py b/tasks/0051_768_51768802_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_768_51768802_qa_2/tests/grader.py +++ b/tasks/0051_768_51768802_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/0052_026_52026780_qa_3/tests/grader.py b/tasks/0052_026_52026780_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_026_52026780_qa_3/tests/grader.py +++ b/tasks/0052_026_52026780_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/0052_331_52331828_qa_4/tests/grader.py b/tasks/0052_331_52331828_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_331_52331828_qa_4/tests/grader.py +++ b/tasks/0052_331_52331828_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_712_52712705_qa_3/tests/grader.py b/tasks/0052_712_52712705_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_712_52712705_qa_3/tests/grader.py +++ b/tasks/0052_712_52712705_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/0052_868_52868101_qa_4/tests/grader.py b/tasks/0052_868_52868101_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_868_52868101_qa_4/tests/grader.py +++ b/tasks/0052_868_52868101_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/0052_868_52868530_qa_4/tests/grader.py b/tasks/0052_868_52868530_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_868_52868530_qa_4/tests/grader.py +++ b/tasks/0052_868_52868530_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/0054_266_54266894_qa_3/tests/grader.py b/tasks/0054_266_54266894_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_266_54266894_qa_3/tests/grader.py +++ b/tasks/0054_266_54266894_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/0054_315_54315694_qa_4/environment/Dockerfile b/tasks/0054_315_54315694_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0054_315_54315694_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0054_315_54315694_qa_4/environment/pull_bucket.py b/tasks/0054_315_54315694_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0054_315_54315694_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/0054_315_54315694_qa_4/tests/grader.py b/tasks/0054_315_54315694_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0054_315_54315694_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/0054_315_54315694_qa_4/tests/test.sh b/tasks/0054_315_54315694_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0054_315_54315694_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/0055_824_55824440_qa_5/tests/grader.py b/tasks/0055_824_55824440_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_824_55824440_qa_5/tests/grader.py +++ b/tasks/0055_824_55824440_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/0055_968_55968459_qa_4/tests/grader.py b/tasks/0055_968_55968459_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_968_55968459_qa_4/tests/grader.py +++ b/tasks/0055_968_55968459_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/0056_410_56410958_qa_4/tests/grader.py b/tasks/0056_410_56410958_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_410_56410958_qa_4/tests/grader.py +++ b/tasks/0056_410_56410958_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/0056_498_56498187_qa_2/tests/grader.py b/tasks/0056_498_56498187_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_498_56498187_qa_2/tests/grader.py +++ b/tasks/0056_498_56498187_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/0058_175_58175407_qa_5/tests/grader.py b/tasks/0058_175_58175407_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0058_175_58175407_qa_5/tests/grader.py +++ b/tasks/0058_175_58175407_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/0058_378_58378917_qa_4/environment/Dockerfile b/tasks/0058_378_58378917_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0058_378_58378917_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0058_378_58378917_qa_4/environment/pull_bucket.py b/tasks/0058_378_58378917_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0058_378_58378917_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/0058_378_58378917_qa_4/tests/grader.py b/tasks/0058_378_58378917_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0058_378_58378917_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/0058_378_58378917_qa_4/tests/test.sh b/tasks/0058_378_58378917_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0058_378_58378917_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/0058_674_58674481_qa_2/tests/grader.py b/tasks/0058_674_58674481_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0058_674_58674481_qa_2/tests/grader.py +++ b/tasks/0058_674_58674481_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/0058_805_58805287_qa_2/tests/grader.py b/tasks/0058_805_58805287_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0058_805_58805287_qa_2/tests/grader.py +++ b/tasks/0058_805_58805287_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/0059_341_59341953_qa_1/tests/grader.py b/tasks/0059_341_59341953_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0059_341_59341953_qa_1/tests/grader.py +++ b/tasks/0059_341_59341953_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/0060_333_60333012_qa_1/tests/grader.py b/tasks/0060_333_60333012_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_333_60333012_qa_1/tests/grader.py +++ b/tasks/0060_333_60333012_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/0061_736_61736140_qa_4/tests/grader.py b/tasks/0061_736_61736140_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_736_61736140_qa_4/tests/grader.py +++ b/tasks/0061_736_61736140_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/0062_450_62450924_qa_2/tests/grader.py b/tasks/0062_450_62450924_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0062_450_62450924_qa_2/tests/grader.py +++ b/tasks/0062_450_62450924_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_836_63836300_qa_1/tests/grader.py b/tasks/0063_836_63836300_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_836_63836300_qa_1/tests/grader.py +++ b/tasks/0063_836_63836300_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/0063_914_63914904_qa_3/tests/grader.py b/tasks/0063_914_63914904_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_914_63914904_qa_3/tests/grader.py +++ b/tasks/0063_914_63914904_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_330_64330026_qa_1/tests/grader.py b/tasks/0064_330_64330026_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_330_64330026_qa_1/tests/grader.py +++ b/tasks/0064_330_64330026_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_397_64397098_qa_3/tests/grader.py b/tasks/0064_397_64397098_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_397_64397098_qa_3/tests/grader.py +++ b/tasks/0064_397_64397098_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_682_64682826_qa_2/tests/grader.py b/tasks/0064_682_64682826_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_682_64682826_qa_2/tests/grader.py +++ b/tasks/0064_682_64682826_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/0064_828_64828278_qa_5/tests/grader.py b/tasks/0064_828_64828278_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_828_64828278_qa_5/tests/grader.py +++ b/tasks/0064_828_64828278_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/0064_907_64907248_qa_1/tests/grader.py b/tasks/0064_907_64907248_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_907_64907248_qa_1/tests/grader.py +++ b/tasks/0064_907_64907248_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_162_65162734_qa_5/tests/grader.py b/tasks/0065_162_65162734_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_162_65162734_qa_5/tests/grader.py +++ b/tasks/0065_162_65162734_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/0065_547_65547031_qa_1/tests/grader.py b/tasks/0065_547_65547031_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_547_65547031_qa_1/tests/grader.py +++ b/tasks/0065_547_65547031_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_756_65756425_qa_1/tests/grader.py b/tasks/0065_756_65756425_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_756_65756425_qa_1/tests/grader.py +++ b/tasks/0065_756_65756425_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/0065_794_65794937_qa_3/environment/Dockerfile b/tasks/0065_794_65794937_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_794_65794937_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_794_65794937_qa_3/environment/pull_bucket.py b/tasks/0065_794_65794937_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_794_65794937_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/0065_794_65794937_qa_3/tests/grader.py b/tasks/0065_794_65794937_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0065_794_65794937_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/0065_794_65794937_qa_3/tests/test.sh b/tasks/0065_794_65794937_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_794_65794937_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/0065_929_65929308_qa_1/tests/grader.py b/tasks/0065_929_65929308_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_929_65929308_qa_1/tests/grader.py +++ b/tasks/0065_929_65929308_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/0066_186_66186009_qa_2/tests/grader.py b/tasks/0066_186_66186009_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0066_186_66186009_qa_2/tests/grader.py +++ b/tasks/0066_186_66186009_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/0066_186_66186009_qa_3/tests/grader.py b/tasks/0066_186_66186009_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0066_186_66186009_qa_3/tests/grader.py +++ b/tasks/0066_186_66186009_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/0066_186_66186009_qa_4/tests/grader.py b/tasks/0066_186_66186009_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0066_186_66186009_qa_4/tests/grader.py +++ b/tasks/0066_186_66186009_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_061_67061270_qa_5/tests/grader.py b/tasks/0067_061_67061270_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_061_67061270_qa_5/tests/grader.py +++ b/tasks/0067_061_67061270_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_247_67247951_qa_2/tests/grader.py b/tasks/0067_247_67247951_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_247_67247951_qa_2/tests/grader.py +++ b/tasks/0067_247_67247951_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/0067_414_67414974_qa_5/tests/grader.py b/tasks/0067_414_67414974_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_414_67414974_qa_5/tests/grader.py +++ b/tasks/0067_414_67414974_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_5/tests/grader.py b/tasks/0067_657_67657879_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_657_67657879_qa_5/tests/grader.py +++ b/tasks/0067_657_67657879_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/0069_293_69293349_qa_2/tests/grader.py b/tasks/0069_293_69293349_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_293_69293349_qa_2/tests/grader.py +++ b/tasks/0069_293_69293349_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/0069_294_69294198_qa_5/tests/grader.py b/tasks/0069_294_69294198_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_294_69294198_qa_5/tests/grader.py +++ b/tasks/0069_294_69294198_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/0071_845_71845804_qa_1/tests/grader.py b/tasks/0071_845_71845804_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0071_845_71845804_qa_1/tests/grader.py +++ b/tasks/0071_845_71845804_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/0072_071_72071082_qa_5/tests/grader.py b/tasks/0072_071_72071082_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0072_071_72071082_qa_5/tests/grader.py +++ b/tasks/0072_071_72071082_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/0072_471_72471518_qa_3/tests/grader.py b/tasks/0072_471_72471518_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0072_471_72471518_qa_3/tests/grader.py +++ b/tasks/0072_471_72471518_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/0072_933_72933038_qa_4/tests/grader.py b/tasks/0072_933_72933038_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0072_933_72933038_qa_4/tests/grader.py +++ b/tasks/0072_933_72933038_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/0074_012_74012086_qa_5/tests/grader.py b/tasks/0074_012_74012086_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_012_74012086_qa_5/tests/grader.py +++ b/tasks/0074_012_74012086_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/0074_129_74129496_qa_2/tests/grader.py b/tasks/0074_129_74129496_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_129_74129496_qa_2/tests/grader.py +++ b/tasks/0074_129_74129496_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/0074_483_74483957_qa_5/tests/grader.py b/tasks/0074_483_74483957_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_483_74483957_qa_5/tests/grader.py +++ b/tasks/0074_483_74483957_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/0074_956_74956806_qa_3/tests/grader.py b/tasks/0074_956_74956806_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_956_74956806_qa_3/tests/grader.py +++ b/tasks/0074_956_74956806_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/0075_094_75094397_qa_1/tests/grader.py b/tasks/0075_094_75094397_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_094_75094397_qa_1/tests/grader.py +++ b/tasks/0075_094_75094397_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/0075_148_75148017_qa_1/tests/grader.py b/tasks/0075_148_75148017_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_148_75148017_qa_1/tests/grader.py +++ b/tasks/0075_148_75148017_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_3/tests/grader.py b/tasks/0075_890_75890673_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_890_75890673_qa_3/tests/grader.py +++ b/tasks/0075_890_75890673_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_100_77100984_qa_3/tests/grader.py b/tasks/0077_100_77100984_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_100_77100984_qa_3/tests/grader.py +++ b/tasks/0077_100_77100984_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/0077_578_77578267_qa_2/tests/grader.py b/tasks/0077_578_77578267_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_578_77578267_qa_2/tests/grader.py +++ b/tasks/0077_578_77578267_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/0077_684_77684454_qa_5/tests/grader.py b/tasks/0077_684_77684454_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_684_77684454_qa_5/tests/grader.py +++ b/tasks/0077_684_77684454_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/0078_779_78779265_qa_1/environment/Dockerfile b/tasks/0078_779_78779265_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0078_779_78779265_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0078_779_78779265_qa_1/environment/pull_bucket.py b/tasks/0078_779_78779265_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0078_779_78779265_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/0078_779_78779265_qa_1/tests/grader.py b/tasks/0078_779_78779265_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0078_779_78779265_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/0078_779_78779265_qa_1/tests/test.sh b/tasks/0078_779_78779265_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0078_779_78779265_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/0080_011_80011409_qa_5/tests/grader.py b/tasks/0080_011_80011409_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0080_011_80011409_qa_5/tests/grader.py +++ b/tasks/0080_011_80011409_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/0081_468_81468620_qa_2/tests/grader.py b/tasks/0081_468_81468620_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0081_468_81468620_qa_2/tests/grader.py +++ b/tasks/0081_468_81468620_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/0083_191_83191425_qa_3/tests/grader.py b/tasks/0083_191_83191425_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0083_191_83191425_qa_3/tests/grader.py +++ b/tasks/0083_191_83191425_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/0083_191_83191425_qa_5/tests/grader.py b/tasks/0083_191_83191425_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0083_191_83191425_qa_5/tests/grader.py +++ b/tasks/0083_191_83191425_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/0083_238_83238182_qa_2/tests/grader.py b/tasks/0083_238_83238182_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0083_238_83238182_qa_2/tests/grader.py +++ b/tasks/0083_238_83238182_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/0083_648_83648661_qa_1/tests/grader.py b/tasks/0083_648_83648661_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0083_648_83648661_qa_1/tests/grader.py +++ b/tasks/0083_648_83648661_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/0085_359_85359585_qa_5/tests/grader.py b/tasks/0085_359_85359585_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_359_85359585_qa_5/tests/grader.py +++ b/tasks/0085_359_85359585_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/0085_451_85451661_qa_2/tests/grader.py b/tasks/0085_451_85451661_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_451_85451661_qa_2/tests/grader.py +++ b/tasks/0085_451_85451661_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/0086_158_86158878_qa_4/tests/grader.py b/tasks/0086_158_86158878_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0086_158_86158878_qa_4/tests/grader.py +++ b/tasks/0086_158_86158878_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/0086_499_86499791_qa_5/tests/grader.py b/tasks/0086_499_86499791_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0086_499_86499791_qa_5/tests/grader.py +++ b/tasks/0086_499_86499791_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/0087_644_87644639_qa_1/tests/grader.py b/tasks/0087_644_87644639_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_644_87644639_qa_1/tests/grader.py +++ b/tasks/0087_644_87644639_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/0088_214_88214420_qa_5/tests/grader.py b/tasks/0088_214_88214420_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0088_214_88214420_qa_5/tests/grader.py +++ b/tasks/0088_214_88214420_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/0088_507_88507841_qa_4/tests/grader.py b/tasks/0088_507_88507841_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0088_507_88507841_qa_4/tests/grader.py +++ b/tasks/0088_507_88507841_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/0088_614_88614765_qa_5/tests/grader.py b/tasks/0088_614_88614765_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0088_614_88614765_qa_5/tests/grader.py +++ b/tasks/0088_614_88614765_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/0091_122_91122496_qa_5/tests/grader.py b/tasks/0091_122_91122496_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_122_91122496_qa_5/tests/grader.py +++ b/tasks/0091_122_91122496_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/0092_354_92354139_qa_3/environment/Dockerfile b/tasks/0092_354_92354139_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0092_354_92354139_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0092_354_92354139_qa_3/environment/pull_bucket.py b/tasks/0092_354_92354139_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0092_354_92354139_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/0092_354_92354139_qa_3/tests/grader.py b/tasks/0092_354_92354139_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0092_354_92354139_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/0092_354_92354139_qa_3/tests/test.sh b/tasks/0092_354_92354139_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0092_354_92354139_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/0093_351_93351284_qa_1/tests/grader.py b/tasks/0093_351_93351284_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0093_351_93351284_qa_1/tests/grader.py +++ b/tasks/0093_351_93351284_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/0093_813_93813737_qa_1/tests/grader.py b/tasks/0093_813_93813737_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0093_813_93813737_qa_1/tests/grader.py +++ b/tasks/0093_813_93813737_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_969_94969707_qa_1/tests/grader.py b/tasks/0094_969_94969707_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0094_969_94969707_qa_1/tests/grader.py +++ b/tasks/0094_969_94969707_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/0095_843_95843375_qa_3/tests/grader.py b/tasks/0095_843_95843375_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0095_843_95843375_qa_3/tests/grader.py +++ b/tasks/0095_843_95843375_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_843_95843375_qa_4/tests/grader.py b/tasks/0095_843_95843375_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0095_843_95843375_qa_4/tests/grader.py +++ b/tasks/0095_843_95843375_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/0095_843_95843375_qa_5/environment/Dockerfile b/tasks/0095_843_95843375_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0095_843_95843375_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0095_843_95843375_qa_5/environment/pull_bucket.py b/tasks/0095_843_95843375_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0095_843_95843375_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/0095_843_95843375_qa_5/tests/grader.py b/tasks/0095_843_95843375_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0095_843_95843375_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/0095_843_95843375_qa_5/tests/test.sh b/tasks/0095_843_95843375_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0095_843_95843375_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/0096_940_96940611_qa_1/tests/grader.py b/tasks/0096_940_96940611_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0096_940_96940611_qa_1/tests/grader.py +++ b/tasks/0096_940_96940611_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/0097_326_97326157_qa_5/tests/grader.py b/tasks/0097_326_97326157_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0097_326_97326157_qa_5/tests/grader.py +++ b/tasks/0097_326_97326157_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/0097_524_97524649_qa_1/tests/grader.py b/tasks/0097_524_97524649_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0097_524_97524649_qa_1/tests/grader.py +++ b/tasks/0097_524_97524649_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/0098_969_98969166_qa_1/tests/grader.py b/tasks/0098_969_98969166_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0098_969_98969166_qa_1/tests/grader.py +++ b/tasks/0098_969_98969166_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/0102_377_102377716_qa_2/tests/grader.py b/tasks/0102_377_102377716_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_377_102377716_qa_2/tests/grader.py +++ b/tasks/0102_377_102377716_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/0102_377_102377716_qa_5/tests/grader.py b/tasks/0102_377_102377716_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_377_102377716_qa_5/tests/grader.py +++ b/tasks/0102_377_102377716_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/0102_436_102436012_qa_1/tests/grader.py b/tasks/0102_436_102436012_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_436_102436012_qa_1/tests/grader.py +++ b/tasks/0102_436_102436012_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/0102_882_102882563_qa_1/tests/grader.py b/tasks/0102_882_102882563_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_882_102882563_qa_1/tests/grader.py +++ b/tasks/0102_882_102882563_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/0103_096_103096538_qa_3/tests/grader.py b/tasks/0103_096_103096538_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_096_103096538_qa_3/tests/grader.py +++ b/tasks/0103_096_103096538_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/0103_147_103147643_qa_3/tests/grader.py b/tasks/0103_147_103147643_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_147_103147643_qa_3/tests/grader.py +++ b/tasks/0103_147_103147643_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_747_103747907_qa_1/tests/grader.py b/tasks/0103_747_103747907_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_747_103747907_qa_1/tests/grader.py +++ b/tasks/0103_747_103747907_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/0104_172_104172936_qa_3/tests/grader.py b/tasks/0104_172_104172936_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_172_104172936_qa_3/tests/grader.py +++ b/tasks/0104_172_104172936_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/0104_399_104399279_qa_1/tests/grader.py b/tasks/0104_399_104399279_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_399_104399279_qa_1/tests/grader.py +++ b/tasks/0104_399_104399279_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/0104_868_104868299_qa_1/tests/grader.py b/tasks/0104_868_104868299_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_868_104868299_qa_1/tests/grader.py +++ b/tasks/0104_868_104868299_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/0105_115_105115907_qa_1/tests/grader.py b/tasks/0105_115_105115907_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_115_105115907_qa_1/tests/grader.py +++ b/tasks/0105_115_105115907_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/0105_131_105131890_qa_4/tests/grader.py b/tasks/0105_131_105131890_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_131_105131890_qa_4/tests/grader.py +++ b/tasks/0105_131_105131890_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/0105_159_105159869_qa_5/tests/grader.py b/tasks/0105_159_105159869_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_159_105159869_qa_5/tests/grader.py +++ b/tasks/0105_159_105159869_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/0105_301_105301672_qa_2/tests/grader.py b/tasks/0105_301_105301672_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_301_105301672_qa_2/tests/grader.py +++ b/tasks/0105_301_105301672_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/0105_684_105684857_qa_5/tests/grader.py b/tasks/0105_684_105684857_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_684_105684857_qa_5/tests/grader.py +++ b/tasks/0105_684_105684857_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/0106_208_106208028_qa_1/tests/grader.py b/tasks/0106_208_106208028_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0106_208_106208028_qa_1/tests/grader.py +++ b/tasks/0106_208_106208028_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/0106_229_106229633_qa_1/tests/grader.py b/tasks/0106_229_106229633_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0106_229_106229633_qa_1/tests/grader.py +++ b/tasks/0106_229_106229633_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/0107_762_107762409_qa_5/tests/grader.py b/tasks/0107_762_107762409_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0107_762_107762409_qa_5/tests/grader.py +++ b/tasks/0107_762_107762409_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_778_108778094_qa_5/tests/grader.py b/tasks/0108_778_108778094_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0108_778_108778094_qa_5/tests/grader.py +++ b/tasks/0108_778_108778094_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/0109_442_109442355_qa_4/tests/grader.py b/tasks/0109_442_109442355_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0109_442_109442355_qa_4/tests/grader.py +++ b/tasks/0109_442_109442355_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/0110_344_110344400_qa_1/tests/grader.py b/tasks/0110_344_110344400_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_344_110344400_qa_1/tests/grader.py +++ b/tasks/0110_344_110344400_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/0111_327_111327287_qa_2/tests/grader.py b/tasks/0111_327_111327287_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0111_327_111327287_qa_2/tests/grader.py +++ b/tasks/0111_327_111327287_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_4/tests/grader.py b/tasks/0111_721_111721771_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0111_721_111721771_qa_4/tests/grader.py +++ b/tasks/0111_721_111721771_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/0112_165_112165295_qa_3/tests/grader.py b/tasks/0112_165_112165295_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0112_165_112165295_qa_3/tests/grader.py +++ b/tasks/0112_165_112165295_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/0113_060_113060572_qa_1/tests/grader.py b/tasks/0113_060_113060572_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_060_113060572_qa_1/tests/grader.py +++ b/tasks/0113_060_113060572_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/0113_124_113124981_qa_5/tests/grader.py b/tasks/0113_124_113124981_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_124_113124981_qa_5/tests/grader.py +++ b/tasks/0113_124_113124981_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/0115_428_115428542_qa_1/tests/grader.py b/tasks/0115_428_115428542_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_428_115428542_qa_1/tests/grader.py +++ b/tasks/0115_428_115428542_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/0115_532_115532151_qa_3/tests/grader.py b/tasks/0115_532_115532151_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_532_115532151_qa_3/tests/grader.py +++ b/tasks/0115_532_115532151_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_972_115972863_qa_1/tests/grader.py b/tasks/0115_972_115972863_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_972_115972863_qa_1/tests/grader.py +++ b/tasks/0115_972_115972863_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/0116_418_116418769_qa_3/tests/grader.py b/tasks/0116_418_116418769_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0116_418_116418769_qa_3/tests/grader.py +++ b/tasks/0116_418_116418769_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/0116_418_116418769_qa_4/tests/grader.py b/tasks/0116_418_116418769_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0116_418_116418769_qa_4/tests/grader.py +++ b/tasks/0116_418_116418769_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/0117_621_117621488_qa_2/tests/grader.py b/tasks/0117_621_117621488_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0117_621_117621488_qa_2/tests/grader.py +++ b/tasks/0117_621_117621488_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/0118_088_118088123_qa_1/tests/grader.py b/tasks/0118_088_118088123_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0118_088_118088123_qa_1/tests/grader.py +++ b/tasks/0118_088_118088123_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/0119_629_119629452_qa_4/tests/grader.py b/tasks/0119_629_119629452_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_629_119629452_qa_4/tests/grader.py +++ b/tasks/0119_629_119629452_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_666_119666168_qa_2/tests/grader.py b/tasks/0119_666_119666168_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_666_119666168_qa_2/tests/grader.py +++ b/tasks/0119_666_119666168_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/0121_603_121603419_qa_3/tests/grader.py b/tasks/0121_603_121603419_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0121_603_121603419_qa_3/tests/grader.py +++ b/tasks/0121_603_121603419_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_030_123030462_qa_4/environment/Dockerfile b/tasks/0123_030_123030462_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0123_030_123030462_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0123_030_123030462_qa_4/environment/pull_bucket.py b/tasks/0123_030_123030462_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0123_030_123030462_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/0123_030_123030462_qa_4/tests/grader.py b/tasks/0123_030_123030462_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0123_030_123030462_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/0123_030_123030462_qa_4/tests/test.sh b/tasks/0123_030_123030462_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0123_030_123030462_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/0123_217_123217664_qa_1/tests/grader.py b/tasks/0123_217_123217664_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_217_123217664_qa_1/tests/grader.py +++ b/tasks/0123_217_123217664_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/0123_672_123672952_qa_2/tests/grader.py b/tasks/0123_672_123672952_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_672_123672952_qa_2/tests/grader.py +++ b/tasks/0123_672_123672952_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/0125_045_125045351_qa_5/tests/grader.py b/tasks/0125_045_125045351_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0125_045_125045351_qa_5/tests/grader.py +++ b/tasks/0125_045_125045351_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/0125_379_125379106_qa_1/tests/grader.py b/tasks/0125_379_125379106_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0125_379_125379106_qa_1/tests/grader.py +++ b/tasks/0125_379_125379106_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/0130_870_130870201_qa_1/tests/grader.py b/tasks/0130_870_130870201_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0130_870_130870201_qa_1/tests/grader.py +++ b/tasks/0130_870_130870201_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/0131_622_131622026_qa_3/tests/grader.py b/tasks/0131_622_131622026_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0131_622_131622026_qa_3/tests/grader.py +++ b/tasks/0131_622_131622026_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/0131_624_131624769_qa_1/tests/grader.py b/tasks/0131_624_131624769_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0131_624_131624769_qa_1/tests/grader.py +++ b/tasks/0131_624_131624769_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/0132_089_132089829_qa_3/tests/grader.py b/tasks/0132_089_132089829_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_089_132089829_qa_3/tests/grader.py +++ b/tasks/0132_089_132089829_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/0132_566_132566728_qa_4/environment/Dockerfile b/tasks/0132_566_132566728_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0132_566_132566728_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0132_566_132566728_qa_4/environment/pull_bucket.py b/tasks/0132_566_132566728_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0132_566_132566728_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/0132_566_132566728_qa_4/tests/grader.py b/tasks/0132_566_132566728_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0132_566_132566728_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/0132_566_132566728_qa_4/tests/test.sh b/tasks/0132_566_132566728_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0132_566_132566728_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/0132_624_132624870_qa_4/tests/grader.py b/tasks/0132_624_132624870_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_624_132624870_qa_4/tests/grader.py +++ b/tasks/0132_624_132624870_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/0133_089_133089049_qa_3/tests/grader.py b/tasks/0133_089_133089049_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0133_089_133089049_qa_3/tests/grader.py +++ b/tasks/0133_089_133089049_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/0133_688_133688260_qa_4/tests/grader.py b/tasks/0133_688_133688260_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0133_688_133688260_qa_4/tests/grader.py +++ b/tasks/0133_688_133688260_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/0134_484_134484147_qa_1/tests/grader.py b/tasks/0134_484_134484147_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0134_484_134484147_qa_1/tests/grader.py +++ b/tasks/0134_484_134484147_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/0134_683_134683130_qa_5/tests/grader.py b/tasks/0134_683_134683130_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0134_683_134683130_qa_5/tests/grader.py +++ b/tasks/0134_683_134683130_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/0134_941_134941943_qa_1/tests/grader.py b/tasks/0134_941_134941943_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0134_941_134941943_qa_1/tests/grader.py +++ b/tasks/0134_941_134941943_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/0135_170_135170219_qa_4/tests/grader.py b/tasks/0135_170_135170219_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_170_135170219_qa_4/tests/grader.py +++ b/tasks/0135_170_135170219_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/0135_674_135674700_qa_5/tests/grader.py b/tasks/0135_674_135674700_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_674_135674700_qa_5/tests/grader.py +++ b/tasks/0135_674_135674700_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/0135_720_135720396_qa_5/tests/grader.py b/tasks/0135_720_135720396_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_720_135720396_qa_5/tests/grader.py +++ b/tasks/0135_720_135720396_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/0135_740_135740732_qa_3/tests/grader.py b/tasks/0135_740_135740732_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_740_135740732_qa_3/tests/grader.py +++ b/tasks/0135_740_135740732_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/0137_769_137769141_qa_4/tests/grader.py b/tasks/0137_769_137769141_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0137_769_137769141_qa_4/tests/grader.py +++ b/tasks/0137_769_137769141_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/0138_684_138684554_qa_2/tests/grader.py b/tasks/0138_684_138684554_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0138_684_138684554_qa_2/tests/grader.py +++ b/tasks/0138_684_138684554_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