diff --git a/tasks/0000_465_465850_qa_5/tests/grader.py b/tasks/0000_465_465850_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0000_465_465850_qa_5/tests/grader.py +++ b/tasks/0000_465_465850_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_074_1074738_qa_1/tests/grader.py b/tasks/0001_074_1074738_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_074_1074738_qa_1/tests/grader.py +++ b/tasks/0001_074_1074738_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_233_1233959_qa_2/tests/grader.py b/tasks/0001_233_1233959_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_233_1233959_qa_2/tests/grader.py +++ b/tasks/0001_233_1233959_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_233_1233959_qa_5/tests/grader.py b/tasks/0001_233_1233959_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_233_1233959_qa_5/tests/grader.py +++ b/tasks/0001_233_1233959_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_364_1364936_qa_3/environment/Dockerfile b/tasks/0001_364_1364936_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_364_1364936_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_364_1364936_qa_3/environment/pull_bucket.py b/tasks/0001_364_1364936_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_364_1364936_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/0001_364_1364936_qa_3/tests/grader.py b/tasks/0001_364_1364936_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0001_364_1364936_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/0001_364_1364936_qa_3/tests/test.sh b/tasks/0001_364_1364936_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_364_1364936_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/0001_364_1364936_qa_4/environment/Dockerfile b/tasks/0001_364_1364936_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_364_1364936_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_364_1364936_qa_4/environment/pull_bucket.py b/tasks/0001_364_1364936_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_364_1364936_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/0001_364_1364936_qa_4/tests/grader.py b/tasks/0001_364_1364936_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0001_364_1364936_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/0001_364_1364936_qa_4/tests/test.sh b/tasks/0001_364_1364936_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_364_1364936_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/0001_374_1374329_qa_3/tests/grader.py b/tasks/0001_374_1374329_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_374_1374329_qa_3/tests/grader.py +++ b/tasks/0001_374_1374329_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_380_1380018_qa_1/tests/grader.py b/tasks/0001_380_1380018_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_380_1380018_qa_1/tests/grader.py +++ b/tasks/0001_380_1380018_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_413_1413239_qa_1/tests/grader.py b/tasks/0001_413_1413239_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_413_1413239_qa_1/tests/grader.py +++ b/tasks/0001_413_1413239_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_426_1426219_qa_4/tests/grader.py b/tasks/0001_426_1426219_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_426_1426219_qa_4/tests/grader.py +++ b/tasks/0001_426_1426219_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_598_1598981_qa_3/tests/grader.py b/tasks/0001_598_1598981_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_598_1598981_qa_3/tests/grader.py +++ b/tasks/0001_598_1598981_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_633_1633600_qa_1/tests/grader.py b/tasks/0001_633_1633600_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_633_1633600_qa_1/tests/grader.py +++ b/tasks/0001_633_1633600_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_662_1662961_qa_3/tests/grader.py b/tasks/0001_662_1662961_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_662_1662961_qa_3/tests/grader.py +++ b/tasks/0001_662_1662961_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_735_1735855_qa_1/tests/grader.py b/tasks/0001_735_1735855_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_735_1735855_qa_1/tests/grader.py +++ b/tasks/0001_735_1735855_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_902_1902242_qa_4/tests/grader.py b/tasks/0001_902_1902242_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_902_1902242_qa_4/tests/grader.py +++ b/tasks/0001_902_1902242_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0001_935_1935106_qa_2/tests/grader.py b/tasks/0001_935_1935106_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_935_1935106_qa_2/tests/grader.py +++ b/tasks/0001_935_1935106_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_956_1956536_qa_4/tests/grader.py b/tasks/0001_956_1956536_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_956_1956536_qa_4/tests/grader.py +++ b/tasks/0001_956_1956536_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_969_1969476_qa_3/tests/grader.py b/tasks/0001_969_1969476_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_969_1969476_qa_3/tests/grader.py +++ b/tasks/0001_969_1969476_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_081_2081941_qa_2/tests/grader.py b/tasks/0002_081_2081941_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_081_2081941_qa_2/tests/grader.py +++ b/tasks/0002_081_2081941_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/0010_489_10489077_qa_4/tests/grader.py b/tasks/0010_489_10489077_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0010_489_10489077_qa_4/tests/grader.py +++ b/tasks/0010_489_10489077_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/0011_763_11763257_qa_2/environment/Dockerfile b/tasks/0011_763_11763257_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0011_763_11763257_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0011_763_11763257_qa_2/environment/pull_bucket.py b/tasks/0011_763_11763257_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0011_763_11763257_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/0011_763_11763257_qa_2/tests/grader.py b/tasks/0011_763_11763257_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0011_763_11763257_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/0011_763_11763257_qa_2/tests/test.sh b/tasks/0011_763_11763257_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0011_763_11763257_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/0012_112_12112066_qa_4/environment/Dockerfile b/tasks/0012_112_12112066_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0012_112_12112066_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0012_112_12112066_qa_4/environment/pull_bucket.py b/tasks/0012_112_12112066_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0012_112_12112066_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/0012_112_12112066_qa_4/tests/grader.py b/tasks/0012_112_12112066_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0012_112_12112066_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/0012_112_12112066_qa_4/tests/test.sh b/tasks/0012_112_12112066_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0012_112_12112066_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/0012_330_12330544_qa_3/tests/grader.py b/tasks/0012_330_12330544_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0012_330_12330544_qa_3/tests/grader.py +++ b/tasks/0012_330_12330544_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/0013_457_13457318_qa_3/tests/grader.py b/tasks/0013_457_13457318_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_457_13457318_qa_3/tests/grader.py +++ b/tasks/0013_457_13457318_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_821_13821679_qa_4/tests/grader.py b/tasks/0013_821_13821679_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_821_13821679_qa_4/tests/grader.py +++ b/tasks/0013_821_13821679_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/0014_115_14115737_qa_1/environment/Dockerfile b/tasks/0014_115_14115737_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0014_115_14115737_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0014_115_14115737_qa_1/environment/pull_bucket.py b/tasks/0014_115_14115737_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0014_115_14115737_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/0014_115_14115737_qa_1/tests/grader.py b/tasks/0014_115_14115737_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0014_115_14115737_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/0014_115_14115737_qa_1/tests/test.sh b/tasks/0014_115_14115737_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0014_115_14115737_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/0014_358_14358635_qa_1/tests/grader.py b/tasks/0014_358_14358635_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0014_358_14358635_qa_1/tests/grader.py +++ b/tasks/0014_358_14358635_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/0015_808_15808353_qa_1/tests/grader.py b/tasks/0015_808_15808353_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0015_808_15808353_qa_1/tests/grader.py +++ b/tasks/0015_808_15808353_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/0015_881_15881525_qa_2/tests/grader.py b/tasks/0015_881_15881525_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0015_881_15881525_qa_2/tests/grader.py +++ b/tasks/0015_881_15881525_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0017_703_17703063_qa_2/environment/Dockerfile b/tasks/0017_703_17703063_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0017_703_17703063_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0017_703_17703063_qa_2/environment/pull_bucket.py b/tasks/0017_703_17703063_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0017_703_17703063_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/0017_703_17703063_qa_2/tests/grader.py b/tasks/0017_703_17703063_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0017_703_17703063_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/0017_703_17703063_qa_2/tests/test.sh b/tasks/0017_703_17703063_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0017_703_17703063_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/0019_416_19416448_qa_4/tests/grader.py b/tasks/0019_416_19416448_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0019_416_19416448_qa_4/tests/grader.py +++ b/tasks/0019_416_19416448_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_395_20395932_qa_4/tests/grader.py b/tasks/0020_395_20395932_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_395_20395932_qa_4/tests/grader.py +++ b/tasks/0020_395_20395932_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/0020_511_20511877_qa_4/tests/grader.py b/tasks/0020_511_20511877_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_511_20511877_qa_4/tests/grader.py +++ b/tasks/0020_511_20511877_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_895_20895805_qa_2/tests/grader.py b/tasks/0020_895_20895805_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_895_20895805_qa_2/tests/grader.py +++ b/tasks/0020_895_20895805_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_145_21145195_qa_3/tests/grader.py b/tasks/0021_145_21145195_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_145_21145195_qa_3/tests/grader.py +++ b/tasks/0021_145_21145195_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/0021_336_21336465_qa_2/tests/grader.py b/tasks/0021_336_21336465_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_336_21336465_qa_2/tests/grader.py +++ b/tasks/0021_336_21336465_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_847_21847371_qa_3/tests/grader.py b/tasks/0021_847_21847371_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_847_21847371_qa_3/tests/grader.py +++ b/tasks/0021_847_21847371_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/0021_873_21873405_qa_2/tests/grader.py b/tasks/0021_873_21873405_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_873_21873405_qa_2/tests/grader.py +++ b/tasks/0021_873_21873405_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0023_531_23531492_qa_5/tests/grader.py b/tasks/0023_531_23531492_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_531_23531492_qa_5/tests/grader.py +++ b/tasks/0023_531_23531492_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/0023_913_23913406_qa_1/tests/grader.py b/tasks/0023_913_23913406_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_913_23913406_qa_1/tests/grader.py +++ b/tasks/0023_913_23913406_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/0025_163_25163859_qa_4/environment/Dockerfile b/tasks/0025_163_25163859_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0025_163_25163859_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0025_163_25163859_qa_4/environment/pull_bucket.py b/tasks/0025_163_25163859_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0025_163_25163859_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/0025_163_25163859_qa_4/tests/grader.py b/tasks/0025_163_25163859_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0025_163_25163859_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/0025_163_25163859_qa_4/tests/test.sh b/tasks/0025_163_25163859_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0025_163_25163859_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/0026_546_26546219_qa_3/tests/grader.py b/tasks/0026_546_26546219_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0026_546_26546219_qa_3/tests/grader.py +++ b/tasks/0026_546_26546219_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/0026_651_26651353_qa_3/tests/grader.py b/tasks/0026_651_26651353_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0026_651_26651353_qa_3/tests/grader.py +++ b/tasks/0026_651_26651353_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/0027_151_27151900_qa_5/tests/grader.py b/tasks/0027_151_27151900_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0027_151_27151900_qa_5/tests/grader.py +++ b/tasks/0027_151_27151900_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_448_29448999_qa_3/tests/grader.py b/tasks/0029_448_29448999_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0029_448_29448999_qa_3/tests/grader.py +++ b/tasks/0029_448_29448999_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/0030_284_30284375_qa_1/tests/grader.py b/tasks/0030_284_30284375_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_284_30284375_qa_1/tests/grader.py +++ b/tasks/0030_284_30284375_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/0031_600_31600148_qa_2/tests/grader.py b/tasks/0031_600_31600148_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_600_31600148_qa_2/tests/grader.py +++ b/tasks/0031_600_31600148_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/0031_852_31852116_qa_2/tests/grader.py b/tasks/0031_852_31852116_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_852_31852116_qa_2/tests/grader.py +++ b/tasks/0031_852_31852116_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0031_872_31872499_qa_4/tests/grader.py b/tasks/0031_872_31872499_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_872_31872499_qa_4/tests/grader.py +++ b/tasks/0031_872_31872499_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/0031_927_31927038_qa_4/tests/grader.py b/tasks/0031_927_31927038_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_927_31927038_qa_4/tests/grader.py +++ b/tasks/0031_927_31927038_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/0032_069_32069437_qa_1/tests/grader.py b/tasks/0032_069_32069437_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_069_32069437_qa_1/tests/grader.py +++ b/tasks/0032_069_32069437_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/0032_178_32178295_qa_2/tests/grader.py b/tasks/0032_178_32178295_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_178_32178295_qa_2/tests/grader.py +++ b/tasks/0032_178_32178295_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/0032_350_32350811_qa_5/tests/grader.py b/tasks/0032_350_32350811_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_350_32350811_qa_5/tests/grader.py +++ b/tasks/0032_350_32350811_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_509_33509634_qa_1/tests/grader.py b/tasks/0033_509_33509634_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_509_33509634_qa_1/tests/grader.py +++ b/tasks/0033_509_33509634_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/0033_652_33652373_qa_2/tests/grader.py b/tasks/0033_652_33652373_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_652_33652373_qa_2/tests/grader.py +++ b/tasks/0033_652_33652373_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_886_34886359_qa_3/tests/grader.py b/tasks/0034_886_34886359_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_886_34886359_qa_3/tests/grader.py +++ b/tasks/0034_886_34886359_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_228_35228737_qa_5/tests/grader.py b/tasks/0035_228_35228737_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_228_35228737_qa_5/tests/grader.py +++ b/tasks/0035_228_35228737_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/0035_337_35337905_qa_1/tests/grader.py b/tasks/0035_337_35337905_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_337_35337905_qa_1/tests/grader.py +++ b/tasks/0035_337_35337905_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/0036_629_36629065_qa_2/tests/grader.py b/tasks/0036_629_36629065_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_629_36629065_qa_2/tests/grader.py +++ b/tasks/0036_629_36629065_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/0036_800_36800377_qa_3/tests/grader.py b/tasks/0036_800_36800377_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_800_36800377_qa_3/tests/grader.py +++ b/tasks/0036_800_36800377_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/0036_800_36800377_qa_4/tests/grader.py b/tasks/0036_800_36800377_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_800_36800377_qa_4/tests/grader.py +++ b/tasks/0036_800_36800377_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/0037_918_37918087_qa_4/tests/grader.py b/tasks/0037_918_37918087_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0037_918_37918087_qa_4/tests/grader.py +++ b/tasks/0037_918_37918087_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0038_159_38159473_qa_4/tests/grader.py b/tasks/0038_159_38159473_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_159_38159473_qa_4/tests/grader.py +++ b/tasks/0038_159_38159473_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/0038_673_38673777_qa_1/tests/grader.py b/tasks/0038_673_38673777_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0038_673_38673777_qa_1/tests/grader.py +++ b/tasks/0038_673_38673777_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/0039_450_39450914_qa_3/tests/grader.py b/tasks/0039_450_39450914_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_450_39450914_qa_3/tests/grader.py +++ b/tasks/0039_450_39450914_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/0039_450_39450914_qa_4/tests/grader.py b/tasks/0039_450_39450914_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_450_39450914_qa_4/tests/grader.py +++ b/tasks/0039_450_39450914_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/0039_715_39715876_qa_1/tests/grader.py b/tasks/0039_715_39715876_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_715_39715876_qa_1/tests/grader.py +++ b/tasks/0039_715_39715876_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/0039_850_39850014_qa_2/tests/grader.py b/tasks/0039_850_39850014_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_850_39850014_qa_2/tests/grader.py +++ b/tasks/0039_850_39850014_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/0040_340_40340401_qa_3/tests/grader.py b/tasks/0040_340_40340401_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_340_40340401_qa_3/tests/grader.py +++ b/tasks/0040_340_40340401_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/0040_340_40340401_qa_4/tests/grader.py b/tasks/0040_340_40340401_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_340_40340401_qa_4/tests/grader.py +++ b/tasks/0040_340_40340401_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_528_40528853_qa_4/tests/grader.py b/tasks/0040_528_40528853_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_528_40528853_qa_4/tests/grader.py +++ b/tasks/0040_528_40528853_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_620_40620313_qa_3/tests/grader.py b/tasks/0040_620_40620313_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_620_40620313_qa_3/tests/grader.py +++ b/tasks/0040_620_40620313_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/0040_736_40736477_qa_3/tests/grader.py b/tasks/0040_736_40736477_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_736_40736477_qa_3/tests/grader.py +++ b/tasks/0040_736_40736477_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0040_826_40826860_qa_1/tests/grader.py b/tasks/0040_826_40826860_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_826_40826860_qa_1/tests/grader.py +++ b/tasks/0040_826_40826860_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/0040_921_40921599_qa_1/tests/grader.py b/tasks/0040_921_40921599_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_921_40921599_qa_1/tests/grader.py +++ b/tasks/0040_921_40921599_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0041_156_41156002_qa_4/tests/grader.py b/tasks/0041_156_41156002_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_156_41156002_qa_4/tests/grader.py +++ b/tasks/0041_156_41156002_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_243_41243008_qa_3/tests/grader.py b/tasks/0041_243_41243008_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_243_41243008_qa_3/tests/grader.py +++ b/tasks/0041_243_41243008_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0041_600_41600293_qa_3/tests/grader.py b/tasks/0041_600_41600293_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_600_41600293_qa_3/tests/grader.py +++ b/tasks/0041_600_41600293_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0041_604_41604680_qa_5/environment/Dockerfile b/tasks/0041_604_41604680_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0041_604_41604680_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0041_604_41604680_qa_5/environment/pull_bucket.py b/tasks/0041_604_41604680_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0041_604_41604680_qa_5/environment/pull_bucket.py @@ -0,0 +1,41 @@ +"""Pull this task's bucket prefix into /home/user/input/. + +Invoked by Harbor's [environment.healthcheck] command (declared in task.toml) +— runs after container start, before the agent. Idempotent: skips work if +files are already present from a prior pull. +""" + +import os +import sys +from pathlib import Path + +from huggingface_hub import download_bucket_files, list_bucket_tree + + +def main() -> int: + bucket = os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all" + prefix = os.environ["BUCKET_PREFIX"].rstrip("/") + "/" + dest = Path("/home/user/input") + dest.mkdir(parents=True, exist_ok=True) + + existing = [p for p in dest.iterdir() if p.is_file()] + if existing: + print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True) + return 0 + + targets = [ + (it.path, str(dest / Path(it.path).name)) + for it in list_bucket_tree(bucket, prefix=prefix, recursive=True) + if getattr(it, "type", None) == "file" + ] + if not targets: + print(f"[pull_bucket] FATAL: no files at hf://buckets/{bucket}/{prefix}", flush=True) + return 2 + + download_bucket_files(bucket, files=targets) + print(f"[pull_bucket] staged {len(targets)} file(s) from {bucket}/{prefix}", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/0041_604_41604680_qa_5/tests/grader.py b/tasks/0041_604_41604680_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0041_604_41604680_qa_5/tests/grader.py @@ -0,0 +1,172 @@ +"""Deterministic short-answer grader v2 — NO LLM judge. + +Tiers (all offline/deterministic): + 1. Exact (case-insensitive, whitespace-collapsed) + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) +""" +from __future__ import annotations +import os, re, sys +from dataclasses import dataclass + +_NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +@dataclass +class GradeResult: + reward: float + method: str + + +def _normalize(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").strip().lower()) + + +def _to_float(s: str): + if not s: + return None + m = _NUMERIC_RE.search(str(s).replace(",", "")) + if not m: + return None + try: + return float(m.group(0)) + except ValueError: + return None + + +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol + + +def _is_clean_number(s: str) -> bool: + t = (s or "").strip().strip("%$").strip().replace(",", "") + return bool(_NUMERIC_RE.fullmatch(t)) + + +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False + + +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: + if not gold or candidate is None: + return GradeResult(0.0, "miss") + + # Tier 1: exact + if _normalize(gold) == _normalize(candidate): + return GradeResult(1.0, "exact") + + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): + g, c = _to_float(gold), _to_float(candidate) + if g is not None and c is not None: + if _num_close(g, c, abs_tol, rel_tol): + return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") + + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify + if _math_verify_match(gold, candidate): + return GradeResult(1.0, "math_verify") + + return GradeResult(0.0, "miss") + + +def _tool_calls(): + try: + with open("/workdir/.n_tool_calls") as fh: + return int(fh.read().strip()) + except (OSError, ValueError): + pass + raw = os.environ.get("N_TOOL_CALLS") + if raw is not None: + try: + return int(str(raw).strip()) + except ValueError: + return None + return None + + +def _tool_efficiency(n): + if n is None: + return None + budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") + if budget <= 0: + return None + return max(0.0, min(1.0, 1.0 - n / budget)) + + +def _tols(): + def _f(name): + try: + return float(os.environ.get(name, "") or 1e-3) + except ValueError: + return 1e-3 + return _f("ATOL"), _f("RTOL") + + +def main_cli() -> int: + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +def main_json() -> int: + import json + gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() + question = (os.environ.get("QUESTION") or "").strip() + candidate = sys.stdin.read().strip() + if not candidate: + print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) + return 0 + at, rt = _tols() + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + if "--json" in sys.argv[1:]: + raise SystemExit(main_json()) + raise SystemExit(main_cli()) diff --git a/tasks/0041_604_41604680_qa_5/tests/test.sh b/tasks/0041_604_41604680_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0041_604_41604680_qa_5/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0042_993_42993650_qa_1/tests/grader.py b/tasks/0042_993_42993650_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_993_42993650_qa_1/tests/grader.py +++ b/tasks/0042_993_42993650_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/0044_270_44270596_qa_4/tests/grader.py b/tasks/0044_270_44270596_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_270_44270596_qa_4/tests/grader.py +++ b/tasks/0044_270_44270596_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0044_401_44401900_qa_3/tests/grader.py b/tasks/0044_401_44401900_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_401_44401900_qa_3/tests/grader.py +++ b/tasks/0044_401_44401900_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/0044_867_44867555_qa_3/tests/grader.py b/tasks/0044_867_44867555_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_867_44867555_qa_3/tests/grader.py +++ b/tasks/0044_867_44867555_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0044_867_44867555_qa_4/tests/grader.py b/tasks/0044_867_44867555_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_867_44867555_qa_4/tests/grader.py +++ b/tasks/0044_867_44867555_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0045_452_45452619_qa_3/tests/grader.py b/tasks/0045_452_45452619_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_452_45452619_qa_3/tests/grader.py +++ b/tasks/0045_452_45452619_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0045_754_45754674_qa_5/tests/grader.py b/tasks/0045_754_45754674_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_754_45754674_qa_5/tests/grader.py +++ b/tasks/0045_754_45754674_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/0045_880_45880804_qa_5/tests/grader.py b/tasks/0045_880_45880804_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_880_45880804_qa_5/tests/grader.py +++ b/tasks/0045_880_45880804_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/0046_333_46333553_qa_1/tests/grader.py b/tasks/0046_333_46333553_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_333_46333553_qa_1/tests/grader.py +++ b/tasks/0046_333_46333553_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_517_46517574_qa_1/tests/grader.py b/tasks/0046_517_46517574_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_517_46517574_qa_1/tests/grader.py +++ b/tasks/0046_517_46517574_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/0046_658_46658315_qa_5/tests/grader.py b/tasks/0046_658_46658315_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_658_46658315_qa_5/tests/grader.py +++ b/tasks/0046_658_46658315_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_905_46905660_qa_1/tests/grader.py b/tasks/0046_905_46905660_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_905_46905660_qa_1/tests/grader.py +++ b/tasks/0046_905_46905660_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/0047_059_47059066_qa_2/tests/grader.py b/tasks/0047_059_47059066_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0047_059_47059066_qa_2/tests/grader.py +++ b/tasks/0047_059_47059066_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/0047_560_47560034_qa_4/tests/grader.py b/tasks/0047_560_47560034_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0047_560_47560034_qa_4/tests/grader.py +++ b/tasks/0047_560_47560034_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_938_49938525_qa_2/tests/grader.py b/tasks/0049_938_49938525_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0049_938_49938525_qa_2/tests/grader.py +++ b/tasks/0049_938_49938525_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_090_50090486_qa_1/tests/grader.py b/tasks/0050_090_50090486_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0050_090_50090486_qa_1/tests/grader.py +++ b/tasks/0050_090_50090486_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/0050_467_50467216_qa_3/tests/grader.py b/tasks/0050_467_50467216_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0050_467_50467216_qa_3/tests/grader.py +++ b/tasks/0050_467_50467216_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/0051_063_51063179_qa_3/tests/grader.py b/tasks/0051_063_51063179_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_063_51063179_qa_3/tests/grader.py +++ b/tasks/0051_063_51063179_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/0051_374_51374286_qa_3/tests/grader.py b/tasks/0051_374_51374286_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_374_51374286_qa_3/tests/grader.py +++ b/tasks/0051_374_51374286_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/0051_880_51880201_qa_3/tests/grader.py b/tasks/0051_880_51880201_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_880_51880201_qa_3/tests/grader.py +++ b/tasks/0051_880_51880201_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/0052_048_52048011_qa_1/tests/grader.py b/tasks/0052_048_52048011_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_048_52048011_qa_1/tests/grader.py +++ b/tasks/0052_048_52048011_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0053_757_53757406_qa_4/environment/Dockerfile b/tasks/0053_757_53757406_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0053_757_53757406_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0053_757_53757406_qa_4/environment/pull_bucket.py b/tasks/0053_757_53757406_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0053_757_53757406_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/0053_757_53757406_qa_4/tests/grader.py b/tasks/0053_757_53757406_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0053_757_53757406_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/0053_757_53757406_qa_4/tests/test.sh b/tasks/0053_757_53757406_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0053_757_53757406_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/0053_823_53823082_qa_3/tests/grader.py b/tasks/0053_823_53823082_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_823_53823082_qa_3/tests/grader.py +++ b/tasks/0053_823_53823082_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0053_823_53823082_qa_4/tests/grader.py b/tasks/0053_823_53823082_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_823_53823082_qa_4/tests/grader.py +++ b/tasks/0053_823_53823082_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/0054_009_54009128_qa_3/environment/Dockerfile b/tasks/0054_009_54009128_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0054_009_54009128_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0054_009_54009128_qa_3/environment/pull_bucket.py b/tasks/0054_009_54009128_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0054_009_54009128_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/0054_009_54009128_qa_3/tests/grader.py b/tasks/0054_009_54009128_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0054_009_54009128_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/0054_009_54009128_qa_3/tests/test.sh b/tasks/0054_009_54009128_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0054_009_54009128_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/0054_375_54375499_qa_5/tests/grader.py b/tasks/0054_375_54375499_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_375_54375499_qa_5/tests/grader.py +++ b/tasks/0054_375_54375499_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0054_473_54473359_qa_4/tests/grader.py b/tasks/0054_473_54473359_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_473_54473359_qa_4/tests/grader.py +++ b/tasks/0054_473_54473359_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/0054_589_54589195_qa_3/environment/Dockerfile b/tasks/0054_589_54589195_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0054_589_54589195_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0054_589_54589195_qa_3/environment/pull_bucket.py b/tasks/0054_589_54589195_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0054_589_54589195_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/0054_589_54589195_qa_3/tests/grader.py b/tasks/0054_589_54589195_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0054_589_54589195_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/0054_589_54589195_qa_3/tests/test.sh b/tasks/0054_589_54589195_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0054_589_54589195_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/0055_033_55033540_qa_1/tests/grader.py b/tasks/0055_033_55033540_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_033_55033540_qa_1/tests/grader.py +++ b/tasks/0055_033_55033540_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/0055_127_55127360_qa_4/tests/grader.py b/tasks/0055_127_55127360_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_127_55127360_qa_4/tests/grader.py +++ b/tasks/0055_127_55127360_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_160_56160021_qa_5/tests/grader.py b/tasks/0056_160_56160021_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_160_56160021_qa_5/tests/grader.py +++ b/tasks/0056_160_56160021_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/0056_876_56876839_qa_5/tests/grader.py b/tasks/0056_876_56876839_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_876_56876839_qa_5/tests/grader.py +++ b/tasks/0056_876_56876839_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/0057_269_57269792_qa_5/tests/grader.py b/tasks/0057_269_57269792_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0057_269_57269792_qa_5/tests/grader.py +++ b/tasks/0057_269_57269792_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/0057_588_57588445_qa_2/tests/grader.py b/tasks/0057_588_57588445_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0057_588_57588445_qa_2/tests/grader.py +++ b/tasks/0057_588_57588445_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/0057_632_57632820_qa_1/tests/grader.py b/tasks/0057_632_57632820_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0057_632_57632820_qa_1/tests/grader.py +++ b/tasks/0057_632_57632820_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/0057_935_57935595_qa_2/tests/grader.py b/tasks/0057_935_57935595_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0057_935_57935595_qa_2/tests/grader.py +++ b/tasks/0057_935_57935595_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_141_59141107_qa_4/environment/Dockerfile b/tasks/0059_141_59141107_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0059_141_59141107_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0059_141_59141107_qa_4/environment/pull_bucket.py b/tasks/0059_141_59141107_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0059_141_59141107_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/0059_141_59141107_qa_4/tests/grader.py b/tasks/0059_141_59141107_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0059_141_59141107_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/0059_141_59141107_qa_4/tests/test.sh b/tasks/0059_141_59141107_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0059_141_59141107_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/0060_059_60059192_qa_1/environment/Dockerfile b/tasks/0060_059_60059192_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0060_059_60059192_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0060_059_60059192_qa_1/environment/pull_bucket.py b/tasks/0060_059_60059192_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0060_059_60059192_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/0060_059_60059192_qa_1/tests/grader.py b/tasks/0060_059_60059192_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0060_059_60059192_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/0060_059_60059192_qa_1/tests/test.sh b/tasks/0060_059_60059192_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0060_059_60059192_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/0060_211_60211356_qa_1/tests/grader.py b/tasks/0060_211_60211356_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_211_60211356_qa_1/tests/grader.py +++ b/tasks/0060_211_60211356_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_435_60435924_qa_2/tests/grader.py b/tasks/0060_435_60435924_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_435_60435924_qa_2/tests/grader.py +++ b/tasks/0060_435_60435924_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/0060_511_60511698_qa_4/tests/grader.py b/tasks/0060_511_60511698_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_511_60511698_qa_4/tests/grader.py +++ b/tasks/0060_511_60511698_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/0060_533_60533129_qa_5/tests/grader.py b/tasks/0060_533_60533129_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_533_60533129_qa_5/tests/grader.py +++ b/tasks/0060_533_60533129_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/0061_292_61292134_qa_2/tests/grader.py b/tasks/0061_292_61292134_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_292_61292134_qa_2/tests/grader.py +++ b/tasks/0061_292_61292134_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/0061_651_61651144_qa_2/tests/grader.py b/tasks/0061_651_61651144_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_651_61651144_qa_2/tests/grader.py +++ b/tasks/0061_651_61651144_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/0061_651_61651144_qa_5/tests/grader.py b/tasks/0061_651_61651144_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_651_61651144_qa_5/tests/grader.py +++ b/tasks/0061_651_61651144_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/0061_702_61702080_qa_4/tests/grader.py b/tasks/0061_702_61702080_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_702_61702080_qa_4/tests/grader.py +++ b/tasks/0061_702_61702080_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/0063_711_63711638_qa_5/tests/grader.py b/tasks/0063_711_63711638_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_711_63711638_qa_5/tests/grader.py +++ b/tasks/0063_711_63711638_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_109_65109957_qa_3/tests/grader.py b/tasks/0065_109_65109957_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_109_65109957_qa_3/tests/grader.py +++ b/tasks/0065_109_65109957_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_337_65337674_qa_4/tests/grader.py b/tasks/0065_337_65337674_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0065_337_65337674_qa_4/tests/grader.py +++ b/tasks/0065_337_65337674_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0065_679_65679925_qa_1/environment/Dockerfile b/tasks/0065_679_65679925_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0065_679_65679925_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0065_679_65679925_qa_1/environment/pull_bucket.py b/tasks/0065_679_65679925_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0065_679_65679925_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/0065_679_65679925_qa_1/tests/grader.py b/tasks/0065_679_65679925_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0065_679_65679925_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/0065_679_65679925_qa_1/tests/test.sh b/tasks/0065_679_65679925_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0065_679_65679925_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/0066_819_66819249_qa_2/tests/grader.py b/tasks/0066_819_66819249_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0066_819_66819249_qa_2/tests/grader.py +++ b/tasks/0066_819_66819249_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_492_67492049_qa_2/tests/grader.py b/tasks/0067_492_67492049_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_492_67492049_qa_2/tests/grader.py +++ b/tasks/0067_492_67492049_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_990_67990197_qa_1/tests/grader.py b/tasks/0067_990_67990197_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_990_67990197_qa_1/tests/grader.py +++ b/tasks/0067_990_67990197_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/0068_119_68119558_qa_5/tests/grader.py b/tasks/0068_119_68119558_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_119_68119558_qa_5/tests/grader.py +++ b/tasks/0068_119_68119558_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/0068_714_68714318_qa_1/tests/grader.py b/tasks/0068_714_68714318_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_714_68714318_qa_1/tests/grader.py +++ b/tasks/0068_714_68714318_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0069_205_69205815_qa_3/tests/grader.py b/tasks/0069_205_69205815_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_205_69205815_qa_3/tests/grader.py +++ b/tasks/0069_205_69205815_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/0071_437_71437256_qa_3/tests/grader.py b/tasks/0071_437_71437256_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0071_437_71437256_qa_3/tests/grader.py +++ b/tasks/0071_437_71437256_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_767_72767167_qa_1/tests/grader.py b/tasks/0072_767_72767167_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0072_767_72767167_qa_1/tests/grader.py +++ b/tasks/0072_767_72767167_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/0073_172_73172053_qa_3/tests/grader.py b/tasks/0073_172_73172053_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_172_73172053_qa_3/tests/grader.py +++ b/tasks/0073_172_73172053_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/0073_430_73430286_qa_3/tests/grader.py b/tasks/0073_430_73430286_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_430_73430286_qa_3/tests/grader.py +++ b/tasks/0073_430_73430286_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/0073_430_73430286_qa_4/tests/grader.py b/tasks/0073_430_73430286_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_430_73430286_qa_4/tests/grader.py +++ b/tasks/0073_430_73430286_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/0073_798_73798390_qa_5/tests/grader.py b/tasks/0073_798_73798390_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_798_73798390_qa_5/tests/grader.py +++ b/tasks/0073_798_73798390_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/0075_174_75174860_qa_3/tests/grader.py b/tasks/0075_174_75174860_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_174_75174860_qa_3/tests/grader.py +++ b/tasks/0075_174_75174860_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/0076_259_76259625_qa_4/tests/grader.py b/tasks/0076_259_76259625_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0076_259_76259625_qa_4/tests/grader.py +++ b/tasks/0076_259_76259625_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/0076_298_76298846_qa_3/tests/grader.py b/tasks/0076_298_76298846_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0076_298_76298846_qa_3/tests/grader.py +++ b/tasks/0076_298_76298846_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/0076_758_76758480_qa_1/tests/grader.py b/tasks/0076_758_76758480_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0076_758_76758480_qa_1/tests/grader.py +++ b/tasks/0076_758_76758480_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/0077_165_77165888_qa_1/tests/grader.py b/tasks/0077_165_77165888_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_165_77165888_qa_1/tests/grader.py +++ b/tasks/0077_165_77165888_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/0077_558_77558936_qa_3/tests/grader.py b/tasks/0077_558_77558936_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_558_77558936_qa_3/tests/grader.py +++ b/tasks/0077_558_77558936_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_854_77854158_qa_2/tests/grader.py b/tasks/0077_854_77854158_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_854_77854158_qa_2/tests/grader.py +++ b/tasks/0077_854_77854158_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/0078_661_78661279_qa_3/tests/grader.py b/tasks/0078_661_78661279_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0078_661_78661279_qa_3/tests/grader.py +++ b/tasks/0078_661_78661279_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0079_606_79606942_qa_1/tests/grader.py b/tasks/0079_606_79606942_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0079_606_79606942_qa_1/tests/grader.py +++ b/tasks/0079_606_79606942_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/0080_705_80705394_qa_1/environment/Dockerfile b/tasks/0080_705_80705394_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0080_705_80705394_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0080_705_80705394_qa_1/environment/pull_bucket.py b/tasks/0080_705_80705394_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0080_705_80705394_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/0080_705_80705394_qa_1/tests/grader.py b/tasks/0080_705_80705394_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0080_705_80705394_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/0080_705_80705394_qa_1/tests/test.sh b/tasks/0080_705_80705394_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0080_705_80705394_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/0081_477_81477923_qa_2/tests/grader.py b/tasks/0081_477_81477923_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0081_477_81477923_qa_2/tests/grader.py +++ b/tasks/0081_477_81477923_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/0081_836_81836619_qa_3/tests/grader.py b/tasks/0081_836_81836619_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0081_836_81836619_qa_3/tests/grader.py +++ b/tasks/0081_836_81836619_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/0082_498_82498397_qa_5/tests/grader.py b/tasks/0082_498_82498397_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0082_498_82498397_qa_5/tests/grader.py +++ b/tasks/0082_498_82498397_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_138_83138273_qa_5/tests/grader.py b/tasks/0083_138_83138273_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0083_138_83138273_qa_5/tests/grader.py +++ b/tasks/0083_138_83138273_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/0083_620_83620010_qa_4/tests/grader.py b/tasks/0083_620_83620010_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0083_620_83620010_qa_4/tests/grader.py +++ b/tasks/0083_620_83620010_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/0083_938_83938085_qa_5/tests/grader.py b/tasks/0083_938_83938085_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0083_938_83938085_qa_5/tests/grader.py +++ b/tasks/0083_938_83938085_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/0084_634_84634252_qa_2/tests/grader.py b/tasks/0084_634_84634252_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0084_634_84634252_qa_2/tests/grader.py +++ b/tasks/0084_634_84634252_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/0084_985_84985340_qa_4/tests/grader.py b/tasks/0084_985_84985340_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0084_985_84985340_qa_4/tests/grader.py +++ b/tasks/0084_985_84985340_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/0085_741_85741385_qa_1/tests/grader.py b/tasks/0085_741_85741385_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_741_85741385_qa_1/tests/grader.py +++ b/tasks/0085_741_85741385_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/0086_608_86608703_qa_3/tests/grader.py b/tasks/0086_608_86608703_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0086_608_86608703_qa_3/tests/grader.py +++ b/tasks/0086_608_86608703_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/0086_608_86608703_qa_4/tests/grader.py b/tasks/0086_608_86608703_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0086_608_86608703_qa_4/tests/grader.py +++ b/tasks/0086_608_86608703_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0087_222_87222139_qa_4/tests/grader.py b/tasks/0087_222_87222139_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_222_87222139_qa_4/tests/grader.py +++ b/tasks/0087_222_87222139_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_300_88300701_qa_3/tests/grader.py b/tasks/0088_300_88300701_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0088_300_88300701_qa_3/tests/grader.py +++ b/tasks/0088_300_88300701_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/0089_026_89026160_qa_4/tests/grader.py b/tasks/0089_026_89026160_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0089_026_89026160_qa_4/tests/grader.py +++ b/tasks/0089_026_89026160_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/0090_327_90327261_qa_5/tests/grader.py b/tasks/0090_327_90327261_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0090_327_90327261_qa_5/tests/grader.py +++ b/tasks/0090_327_90327261_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/0090_428_90428964_qa_4/tests/grader.py b/tasks/0090_428_90428964_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0090_428_90428964_qa_4/tests/grader.py +++ b/tasks/0090_428_90428964_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/0091_670_91670414_qa_3/tests/grader.py b/tasks/0091_670_91670414_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_670_91670414_qa_3/tests/grader.py +++ b/tasks/0091_670_91670414_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/0091_902_91902857_qa_1/tests/grader.py b/tasks/0091_902_91902857_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_902_91902857_qa_1/tests/grader.py +++ b/tasks/0091_902_91902857_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/0092_951_92951855_qa_2/tests/grader.py b/tasks/0092_951_92951855_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0092_951_92951855_qa_2/tests/grader.py +++ b/tasks/0092_951_92951855_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/0093_185_93185105_qa_4/tests/grader.py b/tasks/0093_185_93185105_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0093_185_93185105_qa_4/tests/grader.py +++ b/tasks/0093_185_93185105_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/0094_146_94146987_qa_2/tests/grader.py b/tasks/0094_146_94146987_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0094_146_94146987_qa_2/tests/grader.py +++ b/tasks/0094_146_94146987_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/0094_146_94146987_qa_5/tests/grader.py b/tasks/0094_146_94146987_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0094_146_94146987_qa_5/tests/grader.py +++ b/tasks/0094_146_94146987_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/0095_085_95085137_qa_2/tests/grader.py b/tasks/0095_085_95085137_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0095_085_95085137_qa_2/tests/grader.py +++ b/tasks/0095_085_95085137_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/0096_057_96057481_qa_2/tests/grader.py b/tasks/0096_057_96057481_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0096_057_96057481_qa_2/tests/grader.py +++ b/tasks/0096_057_96057481_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/0097_228_97228368_qa_5/tests/grader.py b/tasks/0097_228_97228368_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0097_228_97228368_qa_5/tests/grader.py +++ b/tasks/0097_228_97228368_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_494_97494334_qa_5/tests/grader.py b/tasks/0097_494_97494334_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0097_494_97494334_qa_5/tests/grader.py +++ b/tasks/0097_494_97494334_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/0098_681_98681805_qa_3/tests/grader.py b/tasks/0098_681_98681805_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0098_681_98681805_qa_3/tests/grader.py +++ b/tasks/0098_681_98681805_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/0098_760_98760521_qa_3/tests/grader.py b/tasks/0098_760_98760521_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0098_760_98760521_qa_3/tests/grader.py +++ b/tasks/0098_760_98760521_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/0100_352_100352234_qa_2/tests/grader.py b/tasks/0100_352_100352234_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0100_352_100352234_qa_2/tests/grader.py +++ b/tasks/0100_352_100352234_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0100_352_100352234_qa_5/tests/grader.py b/tasks/0100_352_100352234_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0100_352_100352234_qa_5/tests/grader.py +++ b/tasks/0100_352_100352234_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/0100_636_100636293_qa_1/tests/grader.py b/tasks/0100_636_100636293_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0100_636_100636293_qa_1/tests/grader.py +++ b/tasks/0100_636_100636293_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0100_715_100715048_qa_2/tests/grader.py b/tasks/0100_715_100715048_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0100_715_100715048_qa_2/tests/grader.py +++ b/tasks/0100_715_100715048_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/0102_128_102128950_qa_1/tests/grader.py b/tasks/0102_128_102128950_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_128_102128950_qa_1/tests/grader.py +++ b/tasks/0102_128_102128950_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/0103_724_103724181_qa_4/tests/grader.py b/tasks/0103_724_103724181_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_724_103724181_qa_4/tests/grader.py +++ b/tasks/0103_724_103724181_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0104_391_104391116_qa_1/tests/grader.py b/tasks/0104_391_104391116_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_391_104391116_qa_1/tests/grader.py +++ b/tasks/0104_391_104391116_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_985_104985612_qa_5/tests/grader.py b/tasks/0104_985_104985612_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_985_104985612_qa_5/tests/grader.py +++ b/tasks/0104_985_104985612_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/0105_059_105059592_qa_2/tests/grader.py b/tasks/0105_059_105059592_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_059_105059592_qa_2/tests/grader.py +++ b/tasks/0105_059_105059592_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_059_105059592_qa_5/tests/grader.py b/tasks/0105_059_105059592_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_059_105059592_qa_5/tests/grader.py +++ b/tasks/0105_059_105059592_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_060_105060710_qa_5/tests/grader.py b/tasks/0105_060_105060710_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_060_105060710_qa_5/tests/grader.py +++ b/tasks/0105_060_105060710_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_135_105135715_qa_3/environment/Dockerfile b/tasks/0105_135_105135715_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0105_135_105135715_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0105_135_105135715_qa_3/environment/pull_bucket.py b/tasks/0105_135_105135715_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0105_135_105135715_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/0105_135_105135715_qa_3/tests/grader.py b/tasks/0105_135_105135715_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0105_135_105135715_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/0105_135_105135715_qa_3/tests/test.sh b/tasks/0105_135_105135715_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0105_135_105135715_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/0105_332_105332394_qa_5/environment/Dockerfile b/tasks/0105_332_105332394_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0105_332_105332394_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0105_332_105332394_qa_5/environment/pull_bucket.py b/tasks/0105_332_105332394_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0105_332_105332394_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/0105_332_105332394_qa_5/tests/grader.py b/tasks/0105_332_105332394_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0105_332_105332394_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/0105_332_105332394_qa_5/tests/test.sh b/tasks/0105_332_105332394_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0105_332_105332394_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/0105_478_105478002_qa_1/tests/grader.py b/tasks/0105_478_105478002_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_478_105478002_qa_1/tests/grader.py +++ b/tasks/0105_478_105478002_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/0106_409_106409576_qa_3/tests/grader.py b/tasks/0106_409_106409576_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0106_409_106409576_qa_3/tests/grader.py +++ b/tasks/0106_409_106409576_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/0106_674_106674377_qa_1/tests/grader.py b/tasks/0106_674_106674377_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0106_674_106674377_qa_1/tests/grader.py +++ b/tasks/0106_674_106674377_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_834_106834319_qa_1/environment/Dockerfile b/tasks/0106_834_106834319_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0106_834_106834319_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0106_834_106834319_qa_1/environment/pull_bucket.py b/tasks/0106_834_106834319_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0106_834_106834319_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/0106_834_106834319_qa_1/tests/grader.py b/tasks/0106_834_106834319_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0106_834_106834319_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/0106_834_106834319_qa_1/tests/test.sh b/tasks/0106_834_106834319_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0106_834_106834319_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/0106_910_106910324_qa_3/tests/grader.py b/tasks/0106_910_106910324_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0106_910_106910324_qa_3/tests/grader.py +++ b/tasks/0106_910_106910324_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/0106_911_106911187_qa_5/tests/grader.py b/tasks/0106_911_106911187_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0106_911_106911187_qa_5/tests/grader.py +++ b/tasks/0106_911_106911187_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/0107_060_107060186_qa_5/tests/grader.py b/tasks/0107_060_107060186_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0107_060_107060186_qa_5/tests/grader.py +++ b/tasks/0107_060_107060186_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/0107_177_107177097_qa_4/environment/Dockerfile b/tasks/0107_177_107177097_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0107_177_107177097_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0107_177_107177097_qa_4/environment/pull_bucket.py b/tasks/0107_177_107177097_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0107_177_107177097_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/0107_177_107177097_qa_4/tests/grader.py b/tasks/0107_177_107177097_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0107_177_107177097_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/0107_177_107177097_qa_4/tests/test.sh b/tasks/0107_177_107177097_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0107_177_107177097_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/0107_327_107327801_qa_1/tests/grader.py b/tasks/0107_327_107327801_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0107_327_107327801_qa_1/tests/grader.py +++ b/tasks/0107_327_107327801_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/0108_138_108138714_qa_1/tests/grader.py b/tasks/0108_138_108138714_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0108_138_108138714_qa_1/tests/grader.py +++ b/tasks/0108_138_108138714_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/0108_184_108184818_qa_3/tests/grader.py b/tasks/0108_184_108184818_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0108_184_108184818_qa_3/tests/grader.py +++ b/tasks/0108_184_108184818_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/0108_825_108825699_qa_3/tests/grader.py b/tasks/0108_825_108825699_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0108_825_108825699_qa_3/tests/grader.py +++ b/tasks/0108_825_108825699_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/0109_079_109079153_qa_1/tests/grader.py b/tasks/0109_079_109079153_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0109_079_109079153_qa_1/tests/grader.py +++ b/tasks/0109_079_109079153_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/0109_211_109211049_qa_5/tests/grader.py b/tasks/0109_211_109211049_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0109_211_109211049_qa_5/tests/grader.py +++ b/tasks/0109_211_109211049_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_469_109469247_qa_3/tests/grader.py b/tasks/0109_469_109469247_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0109_469_109469247_qa_3/tests/grader.py +++ b/tasks/0109_469_109469247_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/0110_464_110464682_qa_2/tests/grader.py b/tasks/0110_464_110464682_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_464_110464682_qa_2/tests/grader.py +++ b/tasks/0110_464_110464682_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/0110_664_110664620_qa_2/tests/grader.py b/tasks/0110_664_110664620_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_664_110664620_qa_2/tests/grader.py +++ b/tasks/0110_664_110664620_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/0110_947_110947489_qa_1/tests/grader.py b/tasks/0110_947_110947489_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_947_110947489_qa_1/tests/grader.py +++ b/tasks/0110_947_110947489_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/0112_536_112536664_qa_4/tests/grader.py b/tasks/0112_536_112536664_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0112_536_112536664_qa_4/tests/grader.py +++ b/tasks/0112_536_112536664_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/0113_075_113075841_qa_2/tests/grader.py b/tasks/0113_075_113075841_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_075_113075841_qa_2/tests/grader.py +++ b/tasks/0113_075_113075841_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/0113_246_113246154_qa_3/tests/grader.py b/tasks/0113_246_113246154_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_246_113246154_qa_3/tests/grader.py +++ b/tasks/0113_246_113246154_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/0115_350_115350781_qa_2/tests/grader.py b/tasks/0115_350_115350781_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_350_115350781_qa_2/tests/grader.py +++ b/tasks/0115_350_115350781_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/0115_410_115410234_qa_2/tests/grader.py b/tasks/0115_410_115410234_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_410_115410234_qa_2/tests/grader.py +++ b/tasks/0115_410_115410234_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/0115_609_115609623_qa_2/tests/grader.py b/tasks/0115_609_115609623_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_609_115609623_qa_2/tests/grader.py +++ b/tasks/0115_609_115609623_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/0115_609_115609623_qa_5/tests/grader.py b/tasks/0115_609_115609623_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_609_115609623_qa_5/tests/grader.py +++ b/tasks/0115_609_115609623_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/0116_220_116220361_qa_4/tests/grader.py b/tasks/0116_220_116220361_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0116_220_116220361_qa_4/tests/grader.py +++ b/tasks/0116_220_116220361_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/0117_445_117445192_qa_5/tests/grader.py b/tasks/0117_445_117445192_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0117_445_117445192_qa_5/tests/grader.py +++ b/tasks/0117_445_117445192_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/0117_642_117642587_qa_5/tests/grader.py b/tasks/0117_642_117642587_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0117_642_117642587_qa_5/tests/grader.py +++ b/tasks/0117_642_117642587_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/0119_289_119289330_qa_4/tests/grader.py b/tasks/0119_289_119289330_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_289_119289330_qa_4/tests/grader.py +++ b/tasks/0119_289_119289330_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/0121_396_121396365_qa_2/tests/grader.py b/tasks/0121_396_121396365_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0121_396_121396365_qa_2/tests/grader.py +++ b/tasks/0121_396_121396365_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/0122_715_122715490_qa_5/tests/grader.py b/tasks/0122_715_122715490_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0122_715_122715490_qa_5/tests/grader.py +++ b/tasks/0122_715_122715490_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/0122_965_122965866_qa_5/environment/Dockerfile b/tasks/0122_965_122965866_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0122_965_122965866_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0122_965_122965866_qa_5/environment/pull_bucket.py b/tasks/0122_965_122965866_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0122_965_122965866_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/0122_965_122965866_qa_5/tests/grader.py b/tasks/0122_965_122965866_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0122_965_122965866_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/0122_965_122965866_qa_5/tests/test.sh b/tasks/0122_965_122965866_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0122_965_122965866_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/0123_625_123625013_qa_5/tests/grader.py b/tasks/0123_625_123625013_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_625_123625013_qa_5/tests/grader.py +++ b/tasks/0123_625_123625013_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/0123_993_123993680_qa_1/tests/grader.py b/tasks/0123_993_123993680_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_993_123993680_qa_1/tests/grader.py +++ b/tasks/0123_993_123993680_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/0124_096_124096448_qa_1/tests/grader.py b/tasks/0124_096_124096448_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0124_096_124096448_qa_1/tests/grader.py +++ b/tasks/0124_096_124096448_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/0124_259_124259674_qa_1/environment/Dockerfile b/tasks/0124_259_124259674_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0124_259_124259674_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0124_259_124259674_qa_1/environment/pull_bucket.py b/tasks/0124_259_124259674_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0124_259_124259674_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/0124_259_124259674_qa_1/tests/grader.py b/tasks/0124_259_124259674_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0124_259_124259674_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/0124_259_124259674_qa_1/tests/test.sh b/tasks/0124_259_124259674_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0124_259_124259674_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/0124_309_124309485_qa_5/tests/grader.py b/tasks/0124_309_124309485_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0124_309_124309485_qa_5/tests/grader.py +++ b/tasks/0124_309_124309485_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/0124_973_124973460_qa_5/tests/grader.py b/tasks/0124_973_124973460_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0124_973_124973460_qa_5/tests/grader.py +++ b/tasks/0124_973_124973460_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/0126_339_126339086_qa_5/tests/grader.py b/tasks/0126_339_126339086_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0126_339_126339086_qa_5/tests/grader.py +++ b/tasks/0126_339_126339086_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/0128_943_128943364_qa_5/tests/grader.py b/tasks/0128_943_128943364_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0128_943_128943364_qa_5/tests/grader.py +++ b/tasks/0128_943_128943364_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/0129_071_129071705_qa_4/environment/Dockerfile b/tasks/0129_071_129071705_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0129_071_129071705_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0129_071_129071705_qa_4/environment/pull_bucket.py b/tasks/0129_071_129071705_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0129_071_129071705_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/0129_071_129071705_qa_4/tests/grader.py b/tasks/0129_071_129071705_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0129_071_129071705_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/0129_071_129071705_qa_4/tests/test.sh b/tasks/0129_071_129071705_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0129_071_129071705_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/0131_433_131433565_qa_4/tests/grader.py b/tasks/0131_433_131433565_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0131_433_131433565_qa_4/tests/grader.py +++ b/tasks/0131_433_131433565_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/0131_552_131552856_qa_4/environment/Dockerfile b/tasks/0131_552_131552856_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0131_552_131552856_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0131_552_131552856_qa_4/environment/pull_bucket.py b/tasks/0131_552_131552856_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0131_552_131552856_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/0131_552_131552856_qa_4/tests/grader.py b/tasks/0131_552_131552856_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0131_552_131552856_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/0131_552_131552856_qa_4/tests/test.sh b/tasks/0131_552_131552856_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0131_552_131552856_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_434_132434308_qa_2/tests/grader.py b/tasks/0132_434_132434308_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_434_132434308_qa_2/tests/grader.py +++ b/tasks/0132_434_132434308_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/0132_642_132642166_qa_2/tests/grader.py b/tasks/0132_642_132642166_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_642_132642166_qa_2/tests/grader.py +++ b/tasks/0132_642_132642166_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/0133_615_133615287_qa_1/tests/grader.py b/tasks/0133_615_133615287_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0133_615_133615287_qa_1/tests/grader.py +++ b/tasks/0133_615_133615287_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/0135_081_135081694_qa_4/tests/grader.py b/tasks/0135_081_135081694_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_081_135081694_qa_4/tests/grader.py +++ b/tasks/0135_081_135081694_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/0135_716_135716121_qa_3/tests/grader.py b/tasks/0135_716_135716121_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_716_135716121_qa_3/tests/grader.py +++ b/tasks/0135_716_135716121_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/0135_968_135968027_qa_1/tests/grader.py b/tasks/0135_968_135968027_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_968_135968027_qa_1/tests/grader.py +++ b/tasks/0135_968_135968027_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/0136_175_136175034_qa_5/tests/grader.py b/tasks/0136_175_136175034_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0136_175_136175034_qa_5/tests/grader.py +++ b/tasks/0136_175_136175034_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/0136_646_136646417_qa_2/tests/grader.py b/tasks/0136_646_136646417_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0136_646_136646417_qa_2/tests/grader.py +++ b/tasks/0136_646_136646417_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/0137_586_137586595_qa_2/tests/grader.py b/tasks/0137_586_137586595_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0137_586_137586595_qa_2/tests/grader.py +++ b/tasks/0137_586_137586595_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/0137_970_137970410_qa_4/tests/grader.py b/tasks/0137_970_137970410_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0137_970_137970410_qa_4/tests/grader.py +++ b/tasks/0137_970_137970410_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_488_138488828_qa_4/tests/grader.py b/tasks/0138_488_138488828_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0138_488_138488828_qa_4/tests/grader.py +++ b/tasks/0138_488_138488828_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/0139_066_139066922_qa_3/tests/grader.py b/tasks/0139_066_139066922_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_066_139066922_qa_3/tests/grader.py +++ b/tasks/0139_066_139066922_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/0139_117_139117477_qa_2/tests/grader.py b/tasks/0139_117_139117477_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_117_139117477_qa_2/tests/grader.py +++ b/tasks/0139_117_139117477_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0139_117_139117477_qa_5/tests/grader.py b/tasks/0139_117_139117477_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_117_139117477_qa_5/tests/grader.py +++ b/tasks/0139_117_139117477_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/0139_181_139181470_qa_3/tests/grader.py b/tasks/0139_181_139181470_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_181_139181470_qa_3/tests/grader.py +++ b/tasks/0139_181_139181470_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