diff --git a/tasks/0000_324_324276_qa_3/tests/grader.py b/tasks/0000_324_324276_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0000_324_324276_qa_3/tests/grader.py +++ b/tasks/0000_324_324276_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/0000_587_587336_qa_5/tests/grader.py b/tasks/0000_587_587336_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0000_587_587336_qa_5/tests/grader.py +++ b/tasks/0000_587_587336_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_262_1262014_qa_4/tests/grader.py b/tasks/0001_262_1262014_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_262_1262014_qa_4/tests/grader.py +++ b/tasks/0001_262_1262014_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_353_1353930_qa_1/tests/grader.py b/tasks/0001_353_1353930_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_353_1353930_qa_1/tests/grader.py +++ b/tasks/0001_353_1353930_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_400_1400936_qa_5/tests/grader.py b/tasks/0001_400_1400936_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_400_1400936_qa_5/tests/grader.py +++ b/tasks/0001_400_1400936_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_473_1473187_qa_4/tests/grader.py b/tasks/0001_473_1473187_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_473_1473187_qa_4/tests/grader.py +++ b/tasks/0001_473_1473187_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_480_1480111_qa_3/tests/grader.py b/tasks/0001_480_1480111_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_480_1480111_qa_3/tests/grader.py +++ b/tasks/0001_480_1480111_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_521_1521206_qa_1/tests/grader.py b/tasks/0001_521_1521206_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_521_1521206_qa_1/tests/grader.py +++ b/tasks/0001_521_1521206_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_593_1593609_qa_5/tests/grader.py b/tasks/0001_593_1593609_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_593_1593609_qa_5/tests/grader.py +++ b/tasks/0001_593_1593609_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_661_1661005_qa_3/environment/Dockerfile b/tasks/0001_661_1661005_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_661_1661005_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_661_1661005_qa_3/environment/pull_bucket.py b/tasks/0001_661_1661005_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_661_1661005_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_661_1661005_qa_3/tests/grader.py b/tasks/0001_661_1661005_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0001_661_1661005_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_661_1661005_qa_3/tests/test.sh b/tasks/0001_661_1661005_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_661_1661005_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_850_1850034_qa_2/environment/Dockerfile b/tasks/0001_850_1850034_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0001_850_1850034_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0001_850_1850034_qa_2/environment/pull_bucket.py b/tasks/0001_850_1850034_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0001_850_1850034_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/0001_850_1850034_qa_2/tests/grader.py b/tasks/0001_850_1850034_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0001_850_1850034_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/0001_850_1850034_qa_2/tests/test.sh b/tasks/0001_850_1850034_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0001_850_1850034_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/0001_850_1850034_qa_5/tests/grader.py b/tasks/0001_850_1850034_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0001_850_1850034_qa_5/tests/grader.py +++ b/tasks/0001_850_1850034_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/0002_105_2105769_qa_3/tests/grader.py b/tasks/0002_105_2105769_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_105_2105769_qa_3/tests/grader.py +++ b/tasks/0002_105_2105769_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_152_2152103_qa_1/tests/grader.py b/tasks/0002_152_2152103_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_152_2152103_qa_1/tests/grader.py +++ b/tasks/0002_152_2152103_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0002_203_2203940_qa_1/tests/grader.py b/tasks/0002_203_2203940_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_203_2203940_qa_1/tests/grader.py +++ b/tasks/0002_203_2203940_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/0002_211_2211506_qa_1/tests/grader.py b/tasks/0002_211_2211506_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0002_211_2211506_qa_1/tests/grader.py +++ b/tasks/0002_211_2211506_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0010_624_10624322_qa_4/tests/grader.py b/tasks/0010_624_10624322_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0010_624_10624322_qa_4/tests/grader.py +++ b/tasks/0010_624_10624322_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/0010_842_10842977_qa_4/tests/grader.py b/tasks/0010_842_10842977_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0010_842_10842977_qa_4/tests/grader.py +++ b/tasks/0010_842_10842977_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/0013_072_13072460_qa_4/tests/grader.py b/tasks/0013_072_13072460_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_072_13072460_qa_4/tests/grader.py +++ b/tasks/0013_072_13072460_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/0013_733_13733964_qa_3/environment/Dockerfile b/tasks/0013_733_13733964_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0013_733_13733964_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0013_733_13733964_qa_3/environment/pull_bucket.py b/tasks/0013_733_13733964_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0013_733_13733964_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/0013_733_13733964_qa_3/tests/grader.py b/tasks/0013_733_13733964_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0013_733_13733964_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/0013_733_13733964_qa_3/tests/test.sh b/tasks/0013_733_13733964_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0013_733_13733964_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/0013_733_13733964_qa_4/tests/grader.py b/tasks/0013_733_13733964_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0013_733_13733964_qa_4/tests/grader.py +++ b/tasks/0013_733_13733964_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/0016_498_16498602_qa_5/tests/grader.py b/tasks/0016_498_16498602_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0016_498_16498602_qa_5/tests/grader.py +++ b/tasks/0016_498_16498602_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/0016_712_16712977_qa_1/tests/grader.py b/tasks/0016_712_16712977_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0016_712_16712977_qa_1/tests/grader.py +++ b/tasks/0016_712_16712977_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/0016_714_16714217_qa_3/tests/grader.py b/tasks/0016_714_16714217_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0016_714_16714217_qa_3/tests/grader.py +++ b/tasks/0016_714_16714217_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/0016_714_16714217_qa_4/tests/grader.py b/tasks/0016_714_16714217_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0016_714_16714217_qa_4/tests/grader.py +++ b/tasks/0016_714_16714217_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/0018_479_18479259_qa_4/tests/grader.py b/tasks/0018_479_18479259_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0018_479_18479259_qa_4/tests/grader.py +++ b/tasks/0018_479_18479259_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/0018_550_18550354_qa_4/tests/grader.py b/tasks/0018_550_18550354_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0018_550_18550354_qa_4/tests/grader.py +++ b/tasks/0018_550_18550354_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_216_20216126_qa_1/tests/grader.py b/tasks/0020_216_20216126_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_216_20216126_qa_1/tests/grader.py +++ b/tasks/0020_216_20216126_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0020_611_20611134_qa_1/tests/grader.py b/tasks/0020_611_20611134_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0020_611_20611134_qa_1/tests/grader.py +++ b/tasks/0020_611_20611134_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0021_193_21193214_qa_1/tests/grader.py b/tasks/0021_193_21193214_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_193_21193214_qa_1/tests/grader.py +++ b/tasks/0021_193_21193214_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0021_636_21636109_qa_2/tests/grader.py b/tasks/0021_636_21636109_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0021_636_21636109_qa_2/tests/grader.py +++ b/tasks/0021_636_21636109_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/0022_193_22193578_qa_1/tests/grader.py b/tasks/0022_193_22193578_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0022_193_22193578_qa_1/tests/grader.py +++ b/tasks/0022_193_22193578_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/0022_916_22916338_qa_1/tests/grader.py b/tasks/0022_916_22916338_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0022_916_22916338_qa_1/tests/grader.py +++ b/tasks/0022_916_22916338_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/0023_186_23186300_qa_1/tests/grader.py b/tasks/0023_186_23186300_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0023_186_23186300_qa_1/tests/grader.py +++ b/tasks/0023_186_23186300_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0024_141_24141442_qa_3/tests/grader.py b/tasks/0024_141_24141442_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_141_24141442_qa_3/tests/grader.py +++ b/tasks/0024_141_24141442_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0024_315_24315892_qa_1/tests/grader.py b/tasks/0024_315_24315892_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_315_24315892_qa_1/tests/grader.py +++ b/tasks/0024_315_24315892_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0024_357_24357086_qa_3/tests/grader.py b/tasks/0024_357_24357086_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0024_357_24357086_qa_3/tests/grader.py +++ b/tasks/0024_357_24357086_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_354_26354042_qa_4/tests/grader.py b/tasks/0026_354_26354042_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0026_354_26354042_qa_4/tests/grader.py +++ b/tasks/0026_354_26354042_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0026_826_26826730_qa_3/tests/grader.py b/tasks/0026_826_26826730_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0026_826_26826730_qa_3/tests/grader.py +++ b/tasks/0026_826_26826730_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/0027_893_27893972_qa_4/tests/grader.py b/tasks/0027_893_27893972_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0027_893_27893972_qa_4/tests/grader.py +++ b/tasks/0027_893_27893972_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/0028_054_28054736_qa_2/tests/grader.py b/tasks/0028_054_28054736_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0028_054_28054736_qa_2/tests/grader.py +++ b/tasks/0028_054_28054736_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/0028_513_28513384_qa_3/tests/grader.py b/tasks/0028_513_28513384_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0028_513_28513384_qa_3/tests/grader.py +++ b/tasks/0028_513_28513384_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/0028_513_28513384_qa_4/tests/grader.py b/tasks/0028_513_28513384_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0028_513_28513384_qa_4/tests/grader.py +++ b/tasks/0028_513_28513384_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/0029_204_29204719_qa_1/tests/grader.py b/tasks/0029_204_29204719_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0029_204_29204719_qa_1/tests/grader.py +++ b/tasks/0029_204_29204719_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0029_650_29650445_qa_3/tests/grader.py b/tasks/0029_650_29650445_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0029_650_29650445_qa_3/tests/grader.py +++ b/tasks/0029_650_29650445_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/0030_144_30144601_qa_2/tests/grader.py b/tasks/0030_144_30144601_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_144_30144601_qa_2/tests/grader.py +++ b/tasks/0030_144_30144601_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0030_304_30304394_qa_5/tests/grader.py b/tasks/0030_304_30304394_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0030_304_30304394_qa_5/tests/grader.py +++ b/tasks/0030_304_30304394_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/0031_829_31829521_qa_4/tests/grader.py b/tasks/0031_829_31829521_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_829_31829521_qa_4/tests/grader.py +++ b/tasks/0031_829_31829521_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_951_31951515_qa_3/tests/grader.py b/tasks/0031_951_31951515_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_951_31951515_qa_3/tests/grader.py +++ b/tasks/0031_951_31951515_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/0031_987_31987709_qa_5/tests/grader.py b/tasks/0031_987_31987709_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0031_987_31987709_qa_5/tests/grader.py +++ b/tasks/0031_987_31987709_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0032_211_32211559_qa_1/environment/Dockerfile b/tasks/0032_211_32211559_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0032_211_32211559_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0032_211_32211559_qa_1/environment/pull_bucket.py b/tasks/0032_211_32211559_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0032_211_32211559_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/0032_211_32211559_qa_1/tests/grader.py b/tasks/0032_211_32211559_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0032_211_32211559_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/0032_211_32211559_qa_1/tests/test.sh b/tasks/0032_211_32211559_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0032_211_32211559_qa_1/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -u +mkdir -p /logs/verifier + +answer_path="/workdir/answer.txt" +if [ ! -s "$answer_path" ]; then + echo "0.0" > /logs/verifier/reward.txt + echo "[grader] no answer at $answer_path" >&2 + exit 0 +fi + +pip install --quiet math-verify >/dev/null 2>&1 || true +python3 /tests/grader.py < "$answer_path" > /logs/verifier/reward.txt diff --git a/tasks/0032_337_32337518_qa_4/tests/grader.py b/tasks/0032_337_32337518_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0032_337_32337518_qa_4/tests/grader.py +++ b/tasks/0032_337_32337518_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0033_703_33703584_qa_3/tests/grader.py b/tasks/0033_703_33703584_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_703_33703584_qa_3/tests/grader.py +++ b/tasks/0033_703_33703584_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/0033_717_33717801_qa_3/tests/grader.py b/tasks/0033_717_33717801_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_717_33717801_qa_3/tests/grader.py +++ b/tasks/0033_717_33717801_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/0033_745_33745374_qa_2/tests/grader.py b/tasks/0033_745_33745374_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0033_745_33745374_qa_2/tests/grader.py +++ b/tasks/0033_745_33745374_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_193_34193226_qa_2/tests/grader.py b/tasks/0034_193_34193226_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_193_34193226_qa_2/tests/grader.py +++ b/tasks/0034_193_34193226_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_295_34295424_qa_1/tests/grader.py b/tasks/0034_295_34295424_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0034_295_34295424_qa_1/tests/grader.py +++ b/tasks/0034_295_34295424_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/0035_236_35236553_qa_1/tests/grader.py b/tasks/0035_236_35236553_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_236_35236553_qa_1/tests/grader.py +++ b/tasks/0035_236_35236553_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0035_370_35370774_qa_3/tests/grader.py b/tasks/0035_370_35370774_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0035_370_35370774_qa_3/tests/grader.py +++ b/tasks/0035_370_35370774_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_510_36510950_qa_4/tests/grader.py b/tasks/0036_510_36510950_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_510_36510950_qa_4/tests/grader.py +++ b/tasks/0036_510_36510950_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/0036_818_36818972_qa_1/tests/grader.py b/tasks/0036_818_36818972_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_818_36818972_qa_1/tests/grader.py +++ b/tasks/0036_818_36818972_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0036_916_36916974_qa_5/tests/grader.py b/tasks/0036_916_36916974_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0036_916_36916974_qa_5/tests/grader.py +++ b/tasks/0036_916_36916974_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/0037_168_37168956_qa_5/tests/grader.py b/tasks/0037_168_37168956_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0037_168_37168956_qa_5/tests/grader.py +++ b/tasks/0037_168_37168956_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/0037_718_37718370_qa_3/environment/Dockerfile b/tasks/0037_718_37718370_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0037_718_37718370_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0037_718_37718370_qa_3/environment/pull_bucket.py b/tasks/0037_718_37718370_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0037_718_37718370_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/0037_718_37718370_qa_3/tests/grader.py b/tasks/0037_718_37718370_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0037_718_37718370_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/0037_718_37718370_qa_3/tests/test.sh b/tasks/0037_718_37718370_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0037_718_37718370_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/0038_900_38900780_qa_5/environment/Dockerfile b/tasks/0038_900_38900780_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0038_900_38900780_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0038_900_38900780_qa_5/environment/pull_bucket.py b/tasks/0038_900_38900780_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0038_900_38900780_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/0038_900_38900780_qa_5/tests/grader.py b/tasks/0038_900_38900780_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0038_900_38900780_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/0038_900_38900780_qa_5/tests/test.sh b/tasks/0038_900_38900780_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0038_900_38900780_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/0039_302_39302156_qa_5/tests/grader.py b/tasks/0039_302_39302156_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_302_39302156_qa_5/tests/grader.py +++ b/tasks/0039_302_39302156_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0039_318_39318025_qa_4/tests/grader.py b/tasks/0039_318_39318025_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_318_39318025_qa_4/tests/grader.py +++ b/tasks/0039_318_39318025_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_785_39785108_qa_1/tests/grader.py b/tasks/0039_785_39785108_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0039_785_39785108_qa_1/tests/grader.py +++ b/tasks/0039_785_39785108_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/0040_418_40418668_qa_4/tests/grader.py b/tasks/0040_418_40418668_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_418_40418668_qa_4/tests/grader.py +++ b/tasks/0040_418_40418668_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/0040_604_40604616_qa_1/tests/grader.py b/tasks/0040_604_40604616_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_604_40604616_qa_1/tests/grader.py +++ b/tasks/0040_604_40604616_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_738_40738491_qa_1/tests/grader.py b/tasks/0040_738_40738491_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_738_40738491_qa_1/tests/grader.py +++ b/tasks/0040_738_40738491_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/0040_756_40756003_qa_2/environment/Dockerfile b/tasks/0040_756_40756003_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0040_756_40756003_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0040_756_40756003_qa_2/environment/pull_bucket.py b/tasks/0040_756_40756003_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0040_756_40756003_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/0040_756_40756003_qa_2/tests/grader.py b/tasks/0040_756_40756003_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0040_756_40756003_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/0040_756_40756003_qa_2/tests/test.sh b/tasks/0040_756_40756003_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0040_756_40756003_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/0040_788_40788057_qa_3/tests/grader.py b/tasks/0040_788_40788057_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0040_788_40788057_qa_3/tests/grader.py +++ b/tasks/0040_788_40788057_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_214_41214331_qa_1/tests/grader.py b/tasks/0041_214_41214331_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_214_41214331_qa_1/tests/grader.py +++ b/tasks/0041_214_41214331_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_314_41314150_qa_1/tests/grader.py b/tasks/0041_314_41314150_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_314_41314150_qa_1/tests/grader.py +++ b/tasks/0041_314_41314150_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_708_41708867_qa_3/tests/grader.py b/tasks/0041_708_41708867_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_708_41708867_qa_3/tests/grader.py +++ b/tasks/0041_708_41708867_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_914_41914023_qa_5/tests/grader.py b/tasks/0041_914_41914023_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0041_914_41914023_qa_5/tests/grader.py +++ b/tasks/0041_914_41914023_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/0042_372_42372757_qa_5/tests/grader.py b/tasks/0042_372_42372757_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_372_42372757_qa_5/tests/grader.py +++ b/tasks/0042_372_42372757_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/0042_750_42750016_qa_1/tests/grader.py b/tasks/0042_750_42750016_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_750_42750016_qa_1/tests/grader.py +++ b/tasks/0042_750_42750016_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0042_806_42806362_qa_1/tests/grader.py b/tasks/0042_806_42806362_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0042_806_42806362_qa_1/tests/grader.py +++ b/tasks/0042_806_42806362_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/0043_374_43374447_qa_2/tests/grader.py b/tasks/0043_374_43374447_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_374_43374447_qa_2/tests/grader.py +++ b/tasks/0043_374_43374447_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/0043_419_43419580_qa_1/tests/grader.py b/tasks/0043_419_43419580_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_419_43419580_qa_1/tests/grader.py +++ b/tasks/0043_419_43419580_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/0043_437_43437842_qa_3/tests/grader.py b/tasks/0043_437_43437842_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_437_43437842_qa_3/tests/grader.py +++ b/tasks/0043_437_43437842_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0043_591_43591690_qa_2/tests/grader.py b/tasks/0043_591_43591690_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0043_591_43591690_qa_2/tests/grader.py +++ b/tasks/0043_591_43591690_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/0044_572_44572407_qa_4/tests/grader.py b/tasks/0044_572_44572407_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_572_44572407_qa_4/tests/grader.py +++ b/tasks/0044_572_44572407_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_766_44766802_qa_2/tests/grader.py b/tasks/0044_766_44766802_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_766_44766802_qa_2/tests/grader.py +++ b/tasks/0044_766_44766802_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0044_873_44873237_qa_3/environment/Dockerfile b/tasks/0044_873_44873237_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0044_873_44873237_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0044_873_44873237_qa_3/environment/pull_bucket.py b/tasks/0044_873_44873237_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0044_873_44873237_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/0044_873_44873237_qa_3/tests/grader.py b/tasks/0044_873_44873237_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0044_873_44873237_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/0044_873_44873237_qa_3/tests/test.sh b/tasks/0044_873_44873237_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0044_873_44873237_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/0044_988_44988061_qa_5/tests/grader.py b/tasks/0044_988_44988061_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0044_988_44988061_qa_5/tests/grader.py +++ b/tasks/0044_988_44988061_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_174_45174378_qa_1/tests/grader.py b/tasks/0045_174_45174378_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0045_174_45174378_qa_1/tests/grader.py +++ b/tasks/0045_174_45174378_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0045_969_45969290_qa_2/environment/Dockerfile b/tasks/0045_969_45969290_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0045_969_45969290_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0045_969_45969290_qa_2/environment/pull_bucket.py b/tasks/0045_969_45969290_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0045_969_45969290_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/0045_969_45969290_qa_2/tests/grader.py b/tasks/0045_969_45969290_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0045_969_45969290_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/0045_969_45969290_qa_2/tests/test.sh b/tasks/0045_969_45969290_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0045_969_45969290_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/0046_305_46305988_qa_2/tests/grader.py b/tasks/0046_305_46305988_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_305_46305988_qa_2/tests/grader.py +++ b/tasks/0046_305_46305988_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/0046_467_46467108_qa_2/tests/grader.py b/tasks/0046_467_46467108_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_467_46467108_qa_2/tests/grader.py +++ b/tasks/0046_467_46467108_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/0046_528_46528108_qa_1/tests/grader.py b/tasks/0046_528_46528108_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0046_528_46528108_qa_1/tests/grader.py +++ b/tasks/0046_528_46528108_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_591_47591946_qa_1/tests/grader.py b/tasks/0047_591_47591946_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0047_591_47591946_qa_1/tests/grader.py +++ b/tasks/0047_591_47591946_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_224_50224594_qa_1/tests/grader.py b/tasks/0050_224_50224594_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0050_224_50224594_qa_1/tests/grader.py +++ b/tasks/0050_224_50224594_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/0050_292_50292896_qa_1/environment/Dockerfile b/tasks/0050_292_50292896_qa_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0050_292_50292896_qa_1/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0050_292_50292896_qa_1/environment/pull_bucket.py b/tasks/0050_292_50292896_qa_1/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0050_292_50292896_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/0050_292_50292896_qa_1/tests/grader.py b/tasks/0050_292_50292896_qa_1/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0050_292_50292896_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/0050_292_50292896_qa_1/tests/test.sh b/tasks/0050_292_50292896_qa_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0050_292_50292896_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/0051_525_51525477_qa_5/tests/grader.py b/tasks/0051_525_51525477_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_525_51525477_qa_5/tests/grader.py +++ b/tasks/0051_525_51525477_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0051_559_51559102_qa_3/tests/grader.py b/tasks/0051_559_51559102_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_559_51559102_qa_3/tests/grader.py +++ b/tasks/0051_559_51559102_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_692_51692011_qa_1/tests/grader.py b/tasks/0051_692_51692011_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_692_51692011_qa_1/tests/grader.py +++ b/tasks/0051_692_51692011_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/0051_990_51990433_qa_2/tests/grader.py b/tasks/0051_990_51990433_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0051_990_51990433_qa_2/tests/grader.py +++ b/tasks/0051_990_51990433_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0052_546_52546501_qa_4/tests/grader.py b/tasks/0052_546_52546501_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_546_52546501_qa_4/tests/grader.py +++ b/tasks/0052_546_52546501_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0052_694_52694962_qa_5/tests/grader.py b/tasks/0052_694_52694962_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_694_52694962_qa_5/tests/grader.py +++ b/tasks/0052_694_52694962_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/0052_868_52868101_qa_1/tests/grader.py b/tasks/0052_868_52868101_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0052_868_52868101_qa_1/tests/grader.py +++ b/tasks/0052_868_52868101_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0053_322_53322838_qa_5/tests/grader.py b/tasks/0053_322_53322838_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_322_53322838_qa_5/tests/grader.py +++ b/tasks/0053_322_53322838_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/0053_603_53603838_qa_2/tests/grader.py b/tasks/0053_603_53603838_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_603_53603838_qa_2/tests/grader.py +++ b/tasks/0053_603_53603838_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/0053_729_53729953_qa_4/tests/grader.py b/tasks/0053_729_53729953_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0053_729_53729953_qa_4/tests/grader.py +++ b/tasks/0053_729_53729953_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0054_170_54170809_qa_3/tests/grader.py b/tasks/0054_170_54170809_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_170_54170809_qa_3/tests/grader.py +++ b/tasks/0054_170_54170809_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/0054_269_54269608_qa_3/tests/grader.py b/tasks/0054_269_54269608_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_269_54269608_qa_3/tests/grader.py +++ b/tasks/0054_269_54269608_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/0054_291_54291213_qa_2/tests/grader.py b/tasks/0054_291_54291213_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_291_54291213_qa_2/tests/grader.py +++ b/tasks/0054_291_54291213_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0054_291_54291213_qa_5/tests/grader.py b/tasks/0054_291_54291213_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0054_291_54291213_qa_5/tests/grader.py +++ b/tasks/0054_291_54291213_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0055_521_55521574_qa_5/tests/grader.py b/tasks/0055_521_55521574_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0055_521_55521574_qa_5/tests/grader.py +++ b/tasks/0055_521_55521574_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_028_56028891_qa_3/tests/grader.py b/tasks/0056_028_56028891_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_028_56028891_qa_3/tests/grader.py +++ b/tasks/0056_028_56028891_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/0056_349_56349410_qa_4/tests/grader.py b/tasks/0056_349_56349410_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0056_349_56349410_qa_4/tests/grader.py +++ b/tasks/0056_349_56349410_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/0058_175_58175546_qa_3/tests/grader.py b/tasks/0058_175_58175546_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0058_175_58175546_qa_3/tests/grader.py +++ b/tasks/0058_175_58175546_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/0058_240_58240435_qa_1/tests/grader.py b/tasks/0058_240_58240435_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0058_240_58240435_qa_1/tests/grader.py +++ b/tasks/0058_240_58240435_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/0059_268_59268311_qa_5/tests/grader.py b/tasks/0059_268_59268311_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0059_268_59268311_qa_5/tests/grader.py +++ b/tasks/0059_268_59268311_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/0060_095_60095066_qa_1/tests/grader.py b/tasks/0060_095_60095066_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_095_60095066_qa_1/tests/grader.py +++ b/tasks/0060_095_60095066_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_220_60220408_qa_3/tests/grader.py b/tasks/0060_220_60220408_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_220_60220408_qa_3/tests/grader.py +++ b/tasks/0060_220_60220408_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/0060_333_60333012_qa_4/tests/grader.py b/tasks/0060_333_60333012_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_333_60333012_qa_4/tests/grader.py +++ b/tasks/0060_333_60333012_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_532_60532216_qa_3/tests/grader.py b/tasks/0060_532_60532216_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_532_60532216_qa_3/tests/grader.py +++ b/tasks/0060_532_60532216_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/0060_532_60532216_qa_4/tests/grader.py b/tasks/0060_532_60532216_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_532_60532216_qa_4/tests/grader.py +++ b/tasks/0060_532_60532216_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/0060_557_60557640_qa_3/tests/grader.py b/tasks/0060_557_60557640_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_557_60557640_qa_3/tests/grader.py +++ b/tasks/0060_557_60557640_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/0060_557_60557640_qa_4/tests/grader.py b/tasks/0060_557_60557640_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_557_60557640_qa_4/tests/grader.py +++ b/tasks/0060_557_60557640_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/0060_702_60702546_qa_2/tests/grader.py b/tasks/0060_702_60702546_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0060_702_60702546_qa_2/tests/grader.py +++ b/tasks/0060_702_60702546_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_220_61220733_qa_2/tests/grader.py b/tasks/0061_220_61220733_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_220_61220733_qa_2/tests/grader.py +++ b/tasks/0061_220_61220733_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/0061_736_61736140_qa_1/tests/grader.py b/tasks/0061_736_61736140_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0061_736_61736140_qa_1/tests/grader.py +++ b/tasks/0061_736_61736140_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/0062_362_62362701_qa_4/tests/grader.py b/tasks/0062_362_62362701_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0062_362_62362701_qa_4/tests/grader.py +++ b/tasks/0062_362_62362701_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0062_986_62986591_qa_2/tests/grader.py b/tasks/0062_986_62986591_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0062_986_62986591_qa_2/tests/grader.py +++ b/tasks/0062_986_62986591_qa_2/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0063_605_63605458_qa_3/tests/grader.py b/tasks/0063_605_63605458_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_605_63605458_qa_3/tests/grader.py +++ b/tasks/0063_605_63605458_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0063_605_63605458_qa_4/tests/grader.py b/tasks/0063_605_63605458_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_605_63605458_qa_4/tests/grader.py +++ b/tasks/0063_605_63605458_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/0063_759_63759604_qa_1/tests/grader.py b/tasks/0063_759_63759604_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_759_63759604_qa_1/tests/grader.py +++ b/tasks/0063_759_63759604_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0063_836_63836300_qa_2/tests/grader.py b/tasks/0063_836_63836300_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0063_836_63836300_qa_2/tests/grader.py +++ b/tasks/0063_836_63836300_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0064_090_64090883_qa_3/tests/grader.py b/tasks/0064_090_64090883_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_090_64090883_qa_3/tests/grader.py +++ b/tasks/0064_090_64090883_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0064_330_64330026_qa_5/tests/grader.py b/tasks/0064_330_64330026_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_330_64330026_qa_5/tests/grader.py +++ b/tasks/0064_330_64330026_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/0064_727_64727238_qa_4/tests/grader.py b/tasks/0064_727_64727238_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_727_64727238_qa_4/tests/grader.py +++ b/tasks/0064_727_64727238_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/0064_851_64851380_qa_2/tests/grader.py b/tasks/0064_851_64851380_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_851_64851380_qa_2/tests/grader.py +++ b/tasks/0064_851_64851380_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0064_907_64907248_qa_2/tests/grader.py b/tasks/0064_907_64907248_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0064_907_64907248_qa_2/tests/grader.py +++ b/tasks/0064_907_64907248_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/0067_485_67485254_qa_4/tests/grader.py b/tasks/0067_485_67485254_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_485_67485254_qa_4/tests/grader.py +++ b/tasks/0067_485_67485254_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/0067_633_67633156_qa_3/tests/grader.py b/tasks/0067_633_67633156_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0067_633_67633156_qa_3/tests/grader.py +++ b/tasks/0067_633_67633156_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0068_111_68111995_qa_1/tests/grader.py b/tasks/0068_111_68111995_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0068_111_68111995_qa_1/tests/grader.py +++ b/tasks/0068_111_68111995_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_054_69054524_qa_2/tests/grader.py b/tasks/0069_054_69054524_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_054_69054524_qa_2/tests/grader.py +++ b/tasks/0069_054_69054524_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0069_142_69142112_qa_4/tests/grader.py b/tasks/0069_142_69142112_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0069_142_69142112_qa_4/tests/grader.py +++ b/tasks/0069_142_69142112_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/0070_120_70120425_qa_3/tests/grader.py b/tasks/0070_120_70120425_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0070_120_70120425_qa_3/tests/grader.py +++ b/tasks/0070_120_70120425_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/0070_874_70874122_qa_5/environment/Dockerfile b/tasks/0070_874_70874122_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0070_874_70874122_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0070_874_70874122_qa_5/environment/pull_bucket.py b/tasks/0070_874_70874122_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0070_874_70874122_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/0070_874_70874122_qa_5/tests/grader.py b/tasks/0070_874_70874122_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0070_874_70874122_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/0070_874_70874122_qa_5/tests/test.sh b/tasks/0070_874_70874122_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0070_874_70874122_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/0070_908_70908084_qa_2/tests/grader.py b/tasks/0070_908_70908084_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0070_908_70908084_qa_2/tests/grader.py +++ b/tasks/0070_908_70908084_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/0071_785_71785724_qa_5/tests/grader.py b/tasks/0071_785_71785724_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0071_785_71785724_qa_5/tests/grader.py +++ b/tasks/0071_785_71785724_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/0071_845_71845804_qa_3/tests/grader.py b/tasks/0071_845_71845804_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0071_845_71845804_qa_3/tests/grader.py +++ b/tasks/0071_845_71845804_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_071_72071082_qa_1/tests/grader.py b/tasks/0072_071_72071082_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0072_071_72071082_qa_1/tests/grader.py +++ b/tasks/0072_071_72071082_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_670_73670678_qa_5/tests/grader.py b/tasks/0073_670_73670678_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0073_670_73670678_qa_5/tests/grader.py +++ b/tasks/0073_670_73670678_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/0074_379_74379604_qa_5/tests/grader.py b/tasks/0074_379_74379604_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_379_74379604_qa_5/tests/grader.py +++ b/tasks/0074_379_74379604_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0074_483_74483957_qa_1/tests/grader.py b/tasks/0074_483_74483957_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_483_74483957_qa_1/tests/grader.py +++ b/tasks/0074_483_74483957_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/0074_705_74705026_qa_1/tests/grader.py b/tasks/0074_705_74705026_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0074_705_74705026_qa_1/tests/grader.py +++ b/tasks/0074_705_74705026_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0075_045_75045566_qa_3/tests/grader.py b/tasks/0075_045_75045566_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_045_75045566_qa_3/tests/grader.py +++ b/tasks/0075_045_75045566_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0075_148_75148017_qa_4/tests/grader.py b/tasks/0075_148_75148017_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_148_75148017_qa_4/tests/grader.py +++ b/tasks/0075_148_75148017_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/0075_765_75765515_qa_5/tests/grader.py b/tasks/0075_765_75765515_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0075_765_75765515_qa_5/tests/grader.py +++ b/tasks/0075_765_75765515_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/0076_359_76359024_qa_1/tests/grader.py b/tasks/0076_359_76359024_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0076_359_76359024_qa_1/tests/grader.py +++ b/tasks/0076_359_76359024_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_167_77167063_qa_4/tests/grader.py b/tasks/0077_167_77167063_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_167_77167063_qa_4/tests/grader.py +++ b/tasks/0077_167_77167063_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0077_322_77322684_qa_3/tests/grader.py b/tasks/0077_322_77322684_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0077_322_77322684_qa_3/tests/grader.py +++ b/tasks/0077_322_77322684_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/0078_483_78483410_qa_3/environment/Dockerfile b/tasks/0078_483_78483410_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0078_483_78483410_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0078_483_78483410_qa_3/environment/pull_bucket.py b/tasks/0078_483_78483410_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0078_483_78483410_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/0078_483_78483410_qa_3/tests/grader.py b/tasks/0078_483_78483410_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0078_483_78483410_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/0078_483_78483410_qa_3/tests/test.sh b/tasks/0078_483_78483410_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0078_483_78483410_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/0079_455_79455690_qa_5/environment/Dockerfile b/tasks/0079_455_79455690_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0079_455_79455690_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0079_455_79455690_qa_5/environment/pull_bucket.py b/tasks/0079_455_79455690_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0079_455_79455690_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/0079_455_79455690_qa_5/tests/grader.py b/tasks/0079_455_79455690_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0079_455_79455690_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/0079_455_79455690_qa_5/tests/test.sh b/tasks/0079_455_79455690_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0079_455_79455690_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/0079_974_79974124_qa_2/tests/grader.py b/tasks/0079_974_79974124_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0079_974_79974124_qa_2/tests/grader.py +++ b/tasks/0079_974_79974124_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/0082_759_82759610_qa_3/tests/grader.py b/tasks/0082_759_82759610_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0082_759_82759610_qa_3/tests/grader.py +++ b/tasks/0082_759_82759610_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_960_82960295_qa_4/tests/grader.py b/tasks/0082_960_82960295_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0082_960_82960295_qa_4/tests/grader.py +++ b/tasks/0082_960_82960295_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_618_83618078_qa_4/tests/grader.py b/tasks/0083_618_83618078_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0083_618_83618078_qa_4/tests/grader.py +++ b/tasks/0083_618_83618078_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/0084_747_84747621_qa_5/tests/grader.py b/tasks/0084_747_84747621_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0084_747_84747621_qa_5/tests/grader.py +++ b/tasks/0084_747_84747621_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_964_84964347_qa_1/tests/grader.py b/tasks/0084_964_84964347_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0084_964_84964347_qa_1/tests/grader.py +++ b/tasks/0084_964_84964347_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/0085_243_85243443_qa_1/tests/grader.py b/tasks/0085_243_85243443_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_243_85243443_qa_1/tests/grader.py +++ b/tasks/0085_243_85243443_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0085_734_85734545_qa_1/tests/grader.py b/tasks/0085_734_85734545_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0085_734_85734545_qa_1/tests/grader.py +++ b/tasks/0085_734_85734545_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0087_388_87388798_qa_4/tests/grader.py b/tasks/0087_388_87388798_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_388_87388798_qa_4/tests/grader.py +++ b/tasks/0087_388_87388798_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_608_87608969_qa_3/tests/grader.py b/tasks/0087_608_87608969_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_608_87608969_qa_3/tests/grader.py +++ b/tasks/0087_608_87608969_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/0087_608_87608969_qa_4/tests/grader.py b/tasks/0087_608_87608969_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0087_608_87608969_qa_4/tests/grader.py +++ b/tasks/0087_608_87608969_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/0087_955_87955720_qa_2/environment/Dockerfile b/tasks/0087_955_87955720_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0087_955_87955720_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0087_955_87955720_qa_2/environment/pull_bucket.py b/tasks/0087_955_87955720_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0087_955_87955720_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/0087_955_87955720_qa_2/tests/grader.py b/tasks/0087_955_87955720_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0087_955_87955720_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/0087_955_87955720_qa_2/tests/test.sh b/tasks/0087_955_87955720_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0087_955_87955720_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/0089_171_89171933_qa_3/tests/grader.py b/tasks/0089_171_89171933_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0089_171_89171933_qa_3/tests/grader.py +++ b/tasks/0089_171_89171933_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_171_89171933_qa_4/tests/grader.py b/tasks/0089_171_89171933_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0089_171_89171933_qa_4/tests/grader.py +++ b/tasks/0089_171_89171933_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/0089_290_89290915_qa_5/tests/grader.py b/tasks/0089_290_89290915_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0089_290_89290915_qa_5/tests/grader.py +++ b/tasks/0089_290_89290915_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/0089_787_89787610_qa_1/tests/grader.py b/tasks/0089_787_89787610_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0089_787_89787610_qa_1/tests/grader.py +++ b/tasks/0089_787_89787610_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/0090_760_90760347_qa_4/tests/grader.py b/tasks/0090_760_90760347_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0090_760_90760347_qa_4/tests/grader.py +++ b/tasks/0090_760_90760347_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/0091_859_91859529_qa_4/tests/grader.py b/tasks/0091_859_91859529_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_859_91859529_qa_4/tests/grader.py +++ b/tasks/0091_859_91859529_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/0091_861_91861304_qa_2/tests/grader.py b/tasks/0091_861_91861304_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0091_861_91861304_qa_2/tests/grader.py +++ b/tasks/0091_861_91861304_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/0092_401_92401680_qa_1/tests/grader.py b/tasks/0092_401_92401680_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0092_401_92401680_qa_1/tests/grader.py +++ b/tasks/0092_401_92401680_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_493_92493148_qa_3/tests/grader.py b/tasks/0092_493_92493148_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0092_493_92493148_qa_3/tests/grader.py +++ b/tasks/0092_493_92493148_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/0093_118_93118701_qa_4/tests/grader.py b/tasks/0093_118_93118701_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0093_118_93118701_qa_4/tests/grader.py +++ b/tasks/0093_118_93118701_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_237_94237964_qa_5/tests/grader.py b/tasks/0094_237_94237964_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0094_237_94237964_qa_5/tests/grader.py +++ b/tasks/0094_237_94237964_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/0094_991_94991853_qa_3/tests/grader.py b/tasks/0094_991_94991853_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0094_991_94991853_qa_3/tests/grader.py +++ b/tasks/0094_991_94991853_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/0096_460_96460762_qa_2/tests/grader.py b/tasks/0096_460_96460762_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0096_460_96460762_qa_2/tests/grader.py +++ b/tasks/0096_460_96460762_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_460_96460762_qa_5/tests/grader.py b/tasks/0096_460_96460762_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0096_460_96460762_qa_5/tests/grader.py +++ b/tasks/0096_460_96460762_qa_5/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0097_014_97014488_qa_2/tests/grader.py b/tasks/0097_014_97014488_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0097_014_97014488_qa_2/tests/grader.py +++ b/tasks/0097_014_97014488_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/0099_222_99222402_qa_3/tests/grader.py b/tasks/0099_222_99222402_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0099_222_99222402_qa_3/tests/grader.py +++ b/tasks/0099_222_99222402_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/0099_334_99334311_qa_4/tests/grader.py b/tasks/0099_334_99334311_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0099_334_99334311_qa_4/tests/grader.py +++ b/tasks/0099_334_99334311_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/0099_540_99540799_qa_1/tests/grader.py b/tasks/0099_540_99540799_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0099_540_99540799_qa_1/tests/grader.py +++ b/tasks/0099_540_99540799_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/0101_787_101787137_qa_5/tests/grader.py b/tasks/0101_787_101787137_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0101_787_101787137_qa_5/tests/grader.py +++ b/tasks/0101_787_101787137_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0102_368_102368775_qa_1/tests/grader.py b/tasks/0102_368_102368775_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_368_102368775_qa_1/tests/grader.py +++ b/tasks/0102_368_102368775_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0102_781_102781194_qa_2/tests/grader.py b/tasks/0102_781_102781194_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_781_102781194_qa_2/tests/grader.py +++ b/tasks/0102_781_102781194_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_919_102919379_qa_1/tests/grader.py b/tasks/0102_919_102919379_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0102_919_102919379_qa_1/tests/grader.py +++ b/tasks/0102_919_102919379_qa_1/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0103_889_103889952_qa_3/tests/grader.py b/tasks/0103_889_103889952_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0103_889_103889952_qa_3/tests/grader.py +++ b/tasks/0103_889_103889952_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0104_399_104399279_qa_3/tests/grader.py b/tasks/0104_399_104399279_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_399_104399279_qa_3/tests/grader.py +++ b/tasks/0104_399_104399279_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/0104_503_104503087_qa_3/tests/grader.py b/tasks/0104_503_104503087_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_503_104503087_qa_3/tests/grader.py +++ b/tasks/0104_503_104503087_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0104_868_104868299_qa_2/tests/grader.py b/tasks/0104_868_104868299_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0104_868_104868299_qa_2/tests/grader.py +++ b/tasks/0104_868_104868299_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/0105_488_105488572_qa_2/tests/grader.py b/tasks/0105_488_105488572_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_488_105488572_qa_2/tests/grader.py +++ b/tasks/0105_488_105488572_qa_2/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0105_684_105684857_qa_1/tests/grader.py b/tasks/0105_684_105684857_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0105_684_105684857_qa_1/tests/grader.py +++ b/tasks/0105_684_105684857_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_598_106598107_qa_5/tests/grader.py b/tasks/0106_598_106598107_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0106_598_106598107_qa_5/tests/grader.py +++ b/tasks/0106_598_106598107_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_073_107073195_qa_2/tests/grader.py b/tasks/0107_073_107073195_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0107_073_107073195_qa_2/tests/grader.py +++ b/tasks/0107_073_107073195_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/0107_417_107417136_qa_4/environment/Dockerfile b/tasks/0107_417_107417136_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0107_417_107417136_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0107_417_107417136_qa_4/environment/pull_bucket.py b/tasks/0107_417_107417136_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0107_417_107417136_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_417_107417136_qa_4/tests/grader.py b/tasks/0107_417_107417136_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0107_417_107417136_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_417_107417136_qa_4/tests/test.sh b/tasks/0107_417_107417136_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0107_417_107417136_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_882_107882051_qa_4/tests/grader.py b/tasks/0107_882_107882051_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0107_882_107882051_qa_4/tests/grader.py +++ b/tasks/0107_882_107882051_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/0108_391_108391946_qa_5/tests/grader.py b/tasks/0108_391_108391946_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0108_391_108391946_qa_5/tests/grader.py +++ b/tasks/0108_391_108391946_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0110_500_110500611_qa_3/tests/grader.py b/tasks/0110_500_110500611_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_500_110500611_qa_3/tests/grader.py +++ b/tasks/0110_500_110500611_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_683_110683455_qa_2/tests/grader.py b/tasks/0110_683_110683455_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_683_110683455_qa_2/tests/grader.py +++ b/tasks/0110_683_110683455_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_774_110774218_qa_3/tests/grader.py b/tasks/0110_774_110774218_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0110_774_110774218_qa_3/tests/grader.py +++ b/tasks/0110_774_110774218_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/0111_071_111071615_qa_5/tests/grader.py b/tasks/0111_071_111071615_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0111_071_111071615_qa_5/tests/grader.py +++ b/tasks/0111_071_111071615_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/0113_068_113068557_qa_1/tests/grader.py b/tasks/0113_068_113068557_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_068_113068557_qa_1/tests/grader.py +++ b/tasks/0113_068_113068557_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0113_222_113222481_qa_1/tests/grader.py b/tasks/0113_222_113222481_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_222_113222481_qa_1/tests/grader.py +++ b/tasks/0113_222_113222481_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0113_996_113996719_qa_4/tests/grader.py b/tasks/0113_996_113996719_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0113_996_113996719_qa_4/tests/grader.py +++ b/tasks/0113_996_113996719_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0115_004_115004067_qa_3/tests/grader.py b/tasks/0115_004_115004067_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_004_115004067_qa_3/tests/grader.py +++ b/tasks/0115_004_115004067_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_004_115004067_qa_4/tests/grader.py b/tasks/0115_004_115004067_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_004_115004067_qa_4/tests/grader.py +++ b/tasks/0115_004_115004067_qa_4/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0115_428_115428542_qa_5/tests/grader.py b/tasks/0115_428_115428542_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_428_115428542_qa_5/tests/grader.py +++ b/tasks/0115_428_115428542_qa_5/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0115_454_115454255_qa_3/tests/grader.py b/tasks/0115_454_115454255_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_454_115454255_qa_3/tests/grader.py +++ b/tasks/0115_454_115454255_qa_3/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0115_567_115567035_qa_5/tests/grader.py b/tasks/0115_567_115567035_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0115_567_115567035_qa_5/tests/grader.py +++ b/tasks/0115_567_115567035_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_195_116195791_qa_2/environment/Dockerfile b/tasks/0116_195_116195791_qa_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0116_195_116195791_qa_2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0116_195_116195791_qa_2/environment/pull_bucket.py b/tasks/0116_195_116195791_qa_2/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0116_195_116195791_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/0116_195_116195791_qa_2/tests/grader.py b/tasks/0116_195_116195791_qa_2/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0116_195_116195791_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/0116_195_116195791_qa_2/tests/test.sh b/tasks/0116_195_116195791_qa_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0116_195_116195791_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/0119_037_119037763_qa_4/tests/grader.py b/tasks/0119_037_119037763_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_037_119037763_qa_4/tests/grader.py +++ b/tasks/0119_037_119037763_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/0119_554_119554814_qa_4/tests/grader.py b/tasks/0119_554_119554814_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_554_119554814_qa_4/tests/grader.py +++ b/tasks/0119_554_119554814_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0119_629_119629452_qa_1/tests/grader.py b/tasks/0119_629_119629452_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0119_629_119629452_qa_1/tests/grader.py +++ b/tasks/0119_629_119629452_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/0120_313_120313409_qa_3/tests/grader.py b/tasks/0120_313_120313409_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0120_313_120313409_qa_3/tests/grader.py +++ b/tasks/0120_313_120313409_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/0120_525_120525286_qa_2/tests/grader.py b/tasks/0120_525_120525286_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0120_525_120525286_qa_2/tests/grader.py +++ b/tasks/0120_525_120525286_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/0121_823_121823327_qa_4/tests/grader.py b/tasks/0121_823_121823327_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0121_823_121823327_qa_4/tests/grader.py +++ b/tasks/0121_823_121823327_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/0121_908_121908423_qa_2/tests/grader.py b/tasks/0121_908_121908423_qa_2/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0121_908_121908423_qa_2/tests/grader.py +++ b/tasks/0121_908_121908423_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/0122_390_122390551_qa_3/tests/grader.py b/tasks/0122_390_122390551_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0122_390_122390551_qa_3/tests/grader.py +++ b/tasks/0122_390_122390551_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/0122_390_122390551_qa_4/tests/grader.py b/tasks/0122_390_122390551_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0122_390_122390551_qa_4/tests/grader.py +++ b/tasks/0122_390_122390551_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/0123_214_123214023_qa_2/tests/grader.py b/tasks/0123_214_123214023_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_214_123214023_qa_2/tests/grader.py +++ b/tasks/0123_214_123214023_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/0123_214_123214023_qa_5/tests/grader.py b/tasks/0123_214_123214023_qa_5/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_214_123214023_qa_5/tests/grader.py +++ b/tasks/0123_214_123214023_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/0123_217_123217664_qa_3/tests/grader.py b/tasks/0123_217_123217664_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_217_123217664_qa_3/tests/grader.py +++ b/tasks/0123_217_123217664_qa_3/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0123_539_123539357_qa_2/tests/grader.py b/tasks/0123_539_123539357_qa_2/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0123_539_123539357_qa_2/tests/grader.py +++ b/tasks/0123_539_123539357_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/0124_384_124384181_qa_1/tests/grader.py b/tasks/0124_384_124384181_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0124_384_124384181_qa_1/tests/grader.py +++ b/tasks/0124_384_124384181_qa_1/tests/grader.py @@ -1,78 +1,34 @@ -"""Shared three-tier grader. +"""Deterministic short-answer grader v2 — NO LLM judge. -Used by both runtimes: - * `env/server.py` — inline inside the `final_answer` ORS @tool method - * `tests/test.sh` — Harbor CLI path; this module is mounted at /tests/grader.py - and invoked with `python3 /tests/grader.py < /workdir/answer.txt` - -Tiers (cheapest → most expensive): +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, accept abs/rel diff ≤ 1e-3) - 3. LLM-judge (gpt-4o-mini, A/B/C verdict, OpenAI simple-evals prompt) - — only invoked if OPENAI_API_KEY is set - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - → reads predicted answer from stdin - → writes a single float ('1.0' or '0.0') to stdout - → exits 0 always; harbor reads stdout from /logs/verifier/reward.txt + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") -# Locked in PLAN.md §"Locked decisions" — adapted from -# https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py -JUDGE_PROMPT = """You are grading short answers from a data-science agent. -Decide whether the predicted answer is semantically equivalent to the gold answer. - -Rules: -- Case, punctuation, whitespace, articles ("the"), and trailing units don't matter. -- For numbers: predicted must match to the last significant figure of the gold - (gold "0.544341", predicted "0.544" -> CORRECT; "0.5" -> INCORRECT). -- Extra surrounding prose is fine if the gold value is clearly stated - (gold "5", predicted "There are 5 distinct categories" -> CORRECT). -- Common synonyms/abbreviations count (gold "Not Applicable", predicted "N/A" -> CORRECT). -- Parenthetical annotations in the gold are equivalence hints, not required - (gold "Gandalf (Ainur)", predicted "Gandalf" -> CORRECT; - gold "No (correlation coefficient = 0.02)", predicted "No" -> CORRECT). -- Percent + qualifier: if the gold is "X% in YEAR", a prediction of X or X% - is CORRECT as long as the core numeric value matches - (gold "21.334% in 2014", predicted "21.334" -> CORRECT; - gold "21.334% in 2014", predicted "21.334% in 2013" -> INCORRECT — year mismatch). -- Multi-part gold like "0.987 (XGBoost and LGBM)" — if the question asks for one - thing (e.g. "which model?"), predicting either listed value is CORRECT. -- If the predicted answer hedges without committing to the gold value -> NOT_ATTEMPTED. -- If it commits to a different value -> INCORRECT. - -Question: {question} -Gold answer: {gold} -Predicted answer: {pred} - -Reply with exactly one token: A (CORRECT), B (INCORRECT), or C (NOT_ATTEMPTED).""" - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -81,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -168,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -194,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0125_045_125045351_qa_1/tests/grader.py b/tasks/0125_045_125045351_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0125_045_125045351_qa_1/tests/grader.py +++ b/tasks/0125_045_125045351_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/0127_137_127137875_qa_4/tests/grader.py b/tasks/0127_137_127137875_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0127_137_127137875_qa_4/tests/grader.py +++ b/tasks/0127_137_127137875_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/0128_996_128996845_qa_3/tests/grader.py b/tasks/0128_996_128996845_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0128_996_128996845_qa_3/tests/grader.py +++ b/tasks/0128_996_128996845_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/0130_713_130713633_qa_5/environment/Dockerfile b/tasks/0130_713_130713633_qa_5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0130_713_130713633_qa_5/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0130_713_130713633_qa_5/environment/pull_bucket.py b/tasks/0130_713_130713633_qa_5/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0130_713_130713633_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/0130_713_130713633_qa_5/tests/grader.py b/tasks/0130_713_130713633_qa_5/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0130_713_130713633_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/0130_713_130713633_qa_5/tests/test.sh b/tasks/0130_713_130713633_qa_5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0130_713_130713633_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/0131_224_131224079_qa_3/environment/Dockerfile b/tasks/0131_224_131224079_qa_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0131_224_131224079_qa_3/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0131_224_131224079_qa_3/environment/pull_bucket.py b/tasks/0131_224_131224079_qa_3/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0131_224_131224079_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/0131_224_131224079_qa_3/tests/grader.py b/tasks/0131_224_131224079_qa_3/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0131_224_131224079_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/0131_224_131224079_qa_3/tests/test.sh b/tasks/0131_224_131224079_qa_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0131_224_131224079_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/0132_236_132236539_qa_5/tests/grader.py b/tasks/0132_236_132236539_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0132_236_132236539_qa_5/tests/grader.py +++ b/tasks/0132_236_132236539_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/0133_586_133586216_qa_3/tests/grader.py b/tasks/0133_586_133586216_qa_3/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0133_586_133586216_qa_3/tests/grader.py +++ b/tasks/0133_586_133586216_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/0133_586_133586216_qa_4/environment/Dockerfile b/tasks/0133_586_133586216_qa_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2384a133285127effba3834747538a4142b9aa4 --- /dev/null +++ b/tasks/0133_586_133586216_qa_4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM docker.io/savatar101/env-data-agent-train:base +WORKDIR /workdir diff --git a/tasks/0133_586_133586216_qa_4/environment/pull_bucket.py b/tasks/0133_586_133586216_qa_4/environment/pull_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..7b495b4b27f7341997aea0b3198b5c31efa785da --- /dev/null +++ b/tasks/0133_586_133586216_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/0133_586_133586216_qa_4/tests/grader.py b/tasks/0133_586_133586216_qa_4/tests/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..3befa9762b926171364dc7e4e3534da4303d8379 --- /dev/null +++ b/tasks/0133_586_133586216_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/0133_586_133586216_qa_4/tests/test.sh b/tasks/0133_586_133586216_qa_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41fe1d00842c487368eec2fc6c387abc2ad5519a --- /dev/null +++ b/tasks/0133_586_133586216_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/0133_988_133988312_qa_4/tests/grader.py b/tasks/0133_988_133988312_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0133_988_133988312_qa_4/tests/grader.py +++ b/tasks/0133_988_133988312_qa_4/tests/grader.py @@ -1,42 +1,34 @@ -"""Deterministic short-answer grader — NO LLM judge. +"""Deterministic short-answer grader v2 — NO LLM judge. -Tiers (cheapest -> most expensive), all offline/deterministic: +Tiers (all offline/deterministic): 1. Exact (case-insensitive, whitespace-collapsed) - 2. Numeric (parse a float, abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) - 3. Math-Verify (symbolic/numeric equivalence via huggingface Math-Verify) - -CLI form (used by tests/test.sh): - EXPECTED_ANSWER='5' QUESTION='How many...' python3 grader.py - -> reads predicted answer from stdin - -> writes a single float ('1.0' or '0.0') to stdout + 2. Numeric (abs/rel tolerance from ATOL/RTOL; gated to clean-number golds) + + percent<->fraction bridge (e.g. gold 96.00 == pred 0.9621) + 3. List (comma-separated): split, strip, order-insensitive; numeric-tolerant per element + (fixes 'a, b' vs 'a,b' spacing and reordering) + 4. Math-Verify (symbolic/numeric equivalence) """ - from __future__ import annotations - -import os -import re -import sys +import os, re, sys from dataclasses import dataclass - _NUMERIC_RE = re.compile(r"-?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") - @dataclass class GradeResult: reward: float - method: str # "exact" | "numeric" | "llm" | "miss" + method: str def _normalize(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) -def _to_float(s: str) -> float | None: +def _to_float(s: str): if not s: return None - m = _NUMERIC_RE.search(s.replace(",", "")) + m = _NUMERIC_RE.search(str(s).replace(",", "")) if not m: return None try: @@ -45,79 +37,76 @@ def _to_float(s: str) -> float | None: return None -def _math_verify_match(gold: str, candidate: str) -> bool: - """Deterministic symbolic/numeric equivalence via HuggingFace Math-Verify. - - Catches equivalences the naive float-parse misses: thousands separators, - fractions (3/4 == 0.75), percentages (50% == 0.5), and symbolic forms. - Fails CLOSED — any parse error / prose gold / timeout returns False (never a - false positive). No network, no LLM. - """ - try: - from math_verify import parse, verify - - return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) - except Exception: # noqa: BLE001 - return False +def _num_close(g, c, abs_tol, rel_tol) -> bool: + return abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol def _is_clean_number(s: str) -> bool: - """True iff the whole string IS a single number (allowing a leading/trailing - %, $, and thousands-commas) — e.g. '95293', '95,293', '0.5', '-3.16', '50%'. - A COMPOUND string like 'Y=3 with 95,293 instances' is NOT a clean number, so - the numeric tier must not fire on it (its `_to_float` would grab the leading - '3' and false-positive-match any answer starting with 3).""" t = (s or "").strip().strip("%$").strip().replace(",", "") return bool(_NUMERIC_RE.fullmatch(t)) -def grade( - gold: str, - candidate: str, - *, - question: str = "", - reward_mode: str = "", - judge: bool = True, # noqa: ARG001 — kept for signature compat; LLM tier removed - judge_model: str | None = None, # noqa: ARG001 - rel_tol: float = 1e-3, - abs_tol: float = 1e-3, -) -> GradeResult: - """Deterministic three-tier match — NO LLM judge. +def _elem_match(a, b, abs_tol, rel_tol) -> bool: + if _normalize(a) == _normalize(b): + return True + fa, fb = _to_float(a), _to_float(b) + if fa is not None and fb is not None: + return _num_close(fa, fb, abs_tol, rel_tol) + return False + + +def _list_match(gold: str, cand: str, abs_tol, rel_tol) -> bool: + gl = [x.strip() for x in gold.split(",") if x.strip()] + cl = [x.strip() for x in cand.split(",") if x.strip()] + if len(gl) < 2 or len(gl) != len(cl): + return False + for gs, cs in ((gl, cl), (sorted(gl, key=str.lower), sorted(cl, key=str.lower))): + if all(_elem_match(a, b, abs_tol, rel_tol) for a, b in zip(gs, cs)): + return True + return False + + +def _math_verify_match(gold: str, candidate: str) -> bool: + try: + from math_verify import parse, verify + return bool(verify(parse(gold), parse(candidate), timeout_seconds=5)) + except Exception: + return False - exact -> numeric (abs_tol/rel_tol, gated to clean-number golds) -> math_verify - -> miss. `judge`/`judge_model` accepted but ignored (LLM tier removed). - """ +def grade(gold: str, candidate: str, *, question: str = "", reward_mode: str = "", + judge: bool = True, judge_model=None, rel_tol: float = 1e-3, abs_tol: float = 1e-3) -> GradeResult: if not gold or candidate is None: return GradeResult(0.0, "miss") - # ── Tier 1: exact (case-insensitive, whitespace-collapsed) ───────── + # Tier 1: exact if _normalize(gold) == _normalize(candidate): return GradeResult(1.0, "exact") - # ── Tier 2: numeric — ONLY when the gold is a single clean number ── - # (compound golds like "Y=3 with 95,293 instances" would otherwise match on - # the leading number; those must go to exact/math_verify, which fail closed). - if reward_mode == "numeric" or _is_clean_number(gold): + # Tier 2: numeric (clean-number gold) + percent/fraction bridge + if reward_mode in ("numeric", "flexible") or _is_clean_number(gold): g, c = _to_float(gold), _to_float(candidate) if g is not None and c is not None: - if abs(g - c) <= abs_tol or abs(g - c) / max(abs(g), 1e-9) <= rel_tol: + if _num_close(g, c, abs_tol, rel_tol): return GradeResult(1.0, "numeric") + # percent<->fraction: one side is a fraction (<1), the other a percent (>=1) + if (0 < abs(c) < 1 <= abs(g)) or (0 < abs(g) < 1 <= abs(c)): + if _num_close(g, c * 100, abs_tol, rel_tol) or _num_close(g, c / 100, abs_tol, rel_tol): + return GradeResult(1.0, "numeric_scaled") - # ── Tier 3: math-verify (symbolic/numeric equivalence, deterministic) ── + # Tier 3: list (comma-separated), order-insensitive, per-element tolerant + if reward_mode in ("list", "list_csv") or ("," in gold and "," in candidate): + if _list_match(gold, candidate, abs_tol, rel_tol): + return GradeResult(1.0, "list") + + # Tier 4: math-verify if _math_verify_match(gold, candidate): return GradeResult(1.0, "math_verify") return GradeResult(0.0, "miss") -def _tool_calls() -> int | None: - """Number of agent tool calls this rollout, for the efficiency reward. - - Written by the harness into the sandbox (`/workdir/.n_tool_calls`); falls - back to the `N_TOOL_CALLS` env var. Returns None if neither is present - (efficiency reward becomes null — the harness didn't report a count). - """ +def _tool_calls(): try: with open("/workdir/.n_tool_calls") as fh: return int(fh.read().strip()) @@ -132,24 +121,17 @@ def _tool_calls() -> int | None: return None -def _tool_efficiency(n_calls: int | None) -> float | None: - """0..1 efficiency signal: fewer tool calls -> higher. None if unknown. - - clip(1 - n_calls / TOOL_BUDGET, 0, 1). TOOL_BUDGET default 15 (solved-4B - median was ~9-10 calls). Raw signal — NOT gated on correctness here; the - RL reward combiner decides gating/weights. - """ - if n_calls is None: +def _tool_efficiency(n): + if n is None: return None budget = float(os.environ.get("TOOL_BUDGET", "15") or "15") if budget <= 0: return None - return max(0.0, min(1.0, 1.0 - n_calls / budget)) + return max(0.0, min(1.0, 1.0 - n / budget)) -def _tols() -> tuple[float, float]: - """Per-task (abs_tol, rel_tol) from ATOL/RTOL in [verifier.env]; 1e-3 default.""" - def _f(name: str) -> float: +def _tols(): + def _f(name): try: return float(os.environ.get(name, "") or 1e-3) except ValueError: @@ -158,60 +140,29 @@ def _tols() -> tuple[float, float]: def main_cli() -> int: - """CLI shim for `tests/test.sh` — env-driven, stdout-only. - - Inputs (via env vars set by Harbor's [verifier.env]): - EXPECTED_ANSWER — the gold - QUESTION — the original question - ATOL / RTOL — per-task numeric tolerances (default 1e-3) - - Predicted answer is read from stdin. - Single float written to stdout. Exit code is always 0. - """ gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - print(f"{result.reward:.1f}") - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={result.reward} method={result.method}", - file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + print(f"{r.reward:.1f}") + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} reward={r.reward} method={r.method}", file=sys.stderr) return 0 def main_json() -> int: - """Multi-reward shim for `tests/test.sh` — writes a `reward.json` dict. - - Three named rewards (Harbor's VerifierResult.rewards carries them all): - correctness — 1.0 iff graded answer matches gold, else 0.0 - submission — 1.0 iff a non-empty answer was submitted, else 0.0 - tool_efficiency — 0..1 (fewer tool calls higher); null if count unknown - - No submission -> all three 0. Predicted answer on stdin; JSON to stdout. - """ import json - gold = (os.environ.get("EXPECTED_ANSWER") or "").strip() question = (os.environ.get("QUESTION") or "").strip() candidate = sys.stdin.read().strip() - if not candidate: print(json.dumps({"correctness": 0.0, "submission": 0.0, "tool_efficiency": 0.0})) - print("[grader] no submission -> all rewards 0", file=sys.stderr) return 0 - at, rt = _tols() - result = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE","") or "", abs_tol=at, rel_tol=rt) - n_calls = _tool_calls() - eff = _tool_efficiency(n_calls) - print(json.dumps({ - "correctness": float(result.reward), - "submission": 1.0, - "tool_efficiency": eff, - })) - print(f"[grader] gold={gold!r} pred={candidate[:80]!r} " - f"correctness={result.reward} method={result.method} " - f"tool_calls={n_calls} tool_efficiency={eff}", file=sys.stderr) + r = grade(gold, candidate, question=question, reward_mode=os.environ.get("REWARD_MODE", "") or "", abs_tol=at, rel_tol=rt) + n = _tool_calls() + print(json.dumps({"correctness": float(r.reward), "submission": 1.0, "tool_efficiency": _tool_efficiency(n)})) + print(f"[grader] gold={gold!r} pred={candidate[:80]!r} correctness={r.reward} method={r.method}", file=sys.stderr) return 0 diff --git a/tasks/0135_720_135720396_qa_1/tests/grader.py b/tasks/0135_720_135720396_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0135_720_135720396_qa_1/tests/grader.py +++ b/tasks/0135_720_135720396_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/0136_677_136677870_qa_1/tests/grader.py b/tasks/0136_677_136677870_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0136_677_136677870_qa_1/tests/grader.py +++ b/tasks/0136_677_136677870_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/0138_103_138103420_qa_4/tests/grader.py b/tasks/0138_103_138103420_qa_4/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0138_103_138103420_qa_4/tests/grader.py +++ b/tasks/0138_103_138103420_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/0138_755_138755530_qa_1/tests/grader.py b/tasks/0138_755_138755530_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0138_755_138755530_qa_1/tests/grader.py +++ b/tasks/0138_755_138755530_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/0138_930_138930992_qa_1/tests/grader.py b/tasks/0138_930_138930992_qa_1/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0138_930_138930992_qa_1/tests/grader.py +++ b/tasks/0138_930_138930992_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/0139_071_139071391_qa_3/tests/grader.py b/tasks/0139_071_139071391_qa_3/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_071_139071391_qa_3/tests/grader.py +++ b/tasks/0139_071_139071391_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/0139_071_139071391_qa_4/tests/grader.py b/tasks/0139_071_139071391_qa_4/tests/grader.py index c2fbd769ded89ae8d27c48849ab4c8f6d6135787..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_071_139071391_qa_4/tests/grader.py +++ b/tasks/0139_071_139071391_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_173_139173112_qa_5/tests/grader.py b/tasks/0139_173_139173112_qa_5/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_173_139173112_qa_5/tests/grader.py +++ b/tasks/0139_173_139173112_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/0139_186_139186690_qa_1/tests/grader.py b/tasks/0139_186_139186690_qa_1/tests/grader.py index 18f167412f6ef590d6785a6b044d3c8027f34038..3befa9762b926171364dc7e4e3534da4303d8379 100644 --- a/tasks/0139_186_139186690_qa_1/tests/grader.py +++ b/tasks/0139_186_139186690_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